iOS UILabel自定義位置

前言

  • 系統(tǒng)Api提供的textAlignment位置我們一般只會用到左邊、右邊、中間三種顯示方式,于是寫個分類提供更多的顯示位置,分別包含左上、右上、左下、右下、中上、中下
  • 采用Category的方式處理,簡單方便使用
GitHub地址:KJCategories

簡單介紹 Property & API

NS_ASSUME_NONNULL_BEGIN
/// Label 文本顯示樣式
typedef NS_ENUM(NSUInteger, KJLabelTextAlignmentType) {
    KJLabelTextAlignmentTypeLeft = 0,
    KJLabelTextAlignmentTypeRight,
    KJLabelTextAlignmentTypeCenter,
    KJLabelTextAlignmentTypeLeftTop,
    KJLabelTextAlignmentTypeRightTop,
    KJLabelTextAlignmentTypeLeftBottom,
    KJLabelTextAlignmentTypeRightBottom,
    KJLabelTextAlignmentTypeTopCenter,
    KJLabelTextAlignmentTypeBottomCenter,
};
@interface UILabel (KJExtension)
/// 設(shè)置文字內(nèi)容顯示位置,外部不需要再去設(shè)置 " textAlignment " 屬性
@property(nonatomic,assign)KJLabelTextAlignmentType kTextAlignmentType;
/// 獲取高度
- (CGFloat)kj_calculateHeightWithWidth:(CGFloat)width;
/// 獲取高度,指定行高
- (CGFloat)kj_calculateHeightWithWidth:(CGFloat)width OneLineHeight:(CGFloat)height;
/// 獲取文字尺寸
+ (CGSize)kj_calculateLabelSizeWithTitle:(NSString*)title font:(UIFont*)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode;

@end

NS_ASSUME_NONNULL_END
1. kTextAlignmentType 設(shè)置文本位置,

這里需要注意的就是內(nèi)部有使用到系統(tǒng)的textAlignment屬性,因此調(diào)用該屬性的話,則不需要調(diào)用textAlignment屬性

使用示例

CGFloat x,y;
CGFloat sp = kAutoW(10);
CGFloat w = (kScreenW-sp*4)/3.;
CGFloat h = w*9/16;
NSArray *names = @[@"左邊",@"右邊",@"中間",@"左上",@"右上",@"左下",@"右下",@"中上",@"中下"];
NSInteger types[9] = {
    KJLabelTextAlignmentTypeLeft,
    KJLabelTextAlignmentTypeRight,
    KJLabelTextAlignmentTypeCenter,
    KJLabelTextAlignmentTypeLeftTop,
    KJLabelTextAlignmentTypeRightTop,
    KJLabelTextAlignmentTypeLeftBottom,
    KJLabelTextAlignmentTypeRightBottom,
    KJLabelTextAlignmentTypeTopCenter,
    KJLabelTextAlignmentTypeBottomCenter
};
for (int k=0; k<names.count; k++) {
    x = k%3*(w+sp)+sp;
    y = k/3*(h+sp)+sp+64+sp*2;
    UILabel *label = [UILabel kj_createLabelWithText:names[k] FontSize:16 TextColor:UIColor.orangeColor];
    label.backgroundColor = [UIColor.orangeColor colorWithAlphaComponent:0.2];
    label.kTextAlignmentType = types[k];
    label.borderWidth = 1;
    label.borderColor = UIColor.orangeColor;
    label.frame = CGRectMake(x, y, w, h);
    [self.view addSubview:label];
}

Category

//
//  UILabel+KJExtension.m
//  KJCategories
//
//  Created by 楊科軍 on 2020/9/24.
//  Copyright ? 2020 楊科軍. All rights reserved.
//  https://github.com/yangKJ/KJExtensionHandler

#import "UILabel+KJExtension.h"
#import <objc/runtime.h>
@implementation UILabel (KJExtension)
- (KJLabelTextAlignmentType)kTextAlignmentType{
    return (KJLabelTextAlignmentType)[objc_getAssociatedObject(self, @selector(kTextAlignmentType)) integerValue];
}
- (void)setKTextAlignmentType:(KJLabelTextAlignmentType)kTextAlignmentType{
    objc_setAssociatedObject(self, @selector(kTextAlignmentType), @(kTextAlignmentType), OBJC_ASSOCIATION_ASSIGN);
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        method_exchangeImplementations(class_getInstanceMethod(self.class, @selector(drawTextInRect:)), class_getInstanceMethod(self.class, @selector(kj_drawTextInRect:)));
    });
    switch (kTextAlignmentType) {
        case KJLabelTextAlignmentTypeRight:
        case KJLabelTextAlignmentTypeRightTop:
        case KJLabelTextAlignmentTypeRightBottom:
            self.textAlignment = NSTextAlignmentRight;
            break;
        case KJLabelTextAlignmentTypeLeft:
        case KJLabelTextAlignmentTypeLeftTop:
        case KJLabelTextAlignmentTypeLeftBottom:
            self.textAlignment = NSTextAlignmentLeft;
            break;
        case KJLabelTextAlignmentTypeCenter:
        case KJLabelTextAlignmentTypeTopCenter:
        case KJLabelTextAlignmentTypeBottomCenter:
            self.textAlignment = NSTextAlignmentCenter;
            break;
        default:
            break;
    }
}
- (void)kj_drawTextInRect:(CGRect)rect{
    switch (self.kTextAlignmentType) {
        case KJLabelTextAlignmentTypeRight:
        case KJLabelTextAlignmentTypeLeft:
        case KJLabelTextAlignmentTypeCenter:
            [self kj_drawTextInRect:rect];
            break;
        case KJLabelTextAlignmentTypeBottomCenter:
        case KJLabelTextAlignmentTypeLeftBottom:
        case KJLabelTextAlignmentTypeRightBottom:{
            CGRect textRect = [self textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines];
            textRect.origin = CGPointMake(textRect.origin.x, -CGRectGetMaxY(textRect)+rect.size.height);
            [self kj_drawTextInRect:textRect];
        }
            break;
        default:{
            CGRect textRect = [self textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines];
            [self kj_drawTextInRect:textRect];
        }
            break;
    }
}

/// 獲取高度
- (CGFloat)kj_calculateHeightWithWidth:(CGFloat)width{
    self.numberOfLines = 0;
    self.lineBreakMode = NSLineBreakByCharWrapping;
    CGSize size = [UILabel kj_calculateLabelSizeWithTitle:self.text font:self.font constrainedToSize:CGSizeMake(width, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];
    size.height += 3;
    return size.height;
}
/// 獲取高度,指定行高
- (CGFloat)kj_calculateHeightWithWidth:(CGFloat)width OneLineHeight:(CGFloat)height{
    self.numberOfLines = 0;
    self.lineBreakMode = NSLineBreakByCharWrapping;
    CGSize size = [UILabel kj_calculateLabelSizeWithTitle:self.text font:self.font constrainedToSize:CGSizeMake(width, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];
    return size.height * height / self.font.lineHeight;
}
/// 獲取文字尺寸
+ (CGSize)kj_calculateLabelSizeWithTitle:(NSString*)title font:(UIFont*)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode{
    if (title.length == 0) return CGSizeZero;
    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
    paragraph.lineBreakMode = lineBreakMode;
    CGRect frame = [title boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font,NSParagraphStyleAttributeName:paragraph} context:nil];
    return frame.size;
}

@end

備注:本文用到的部分函數(shù)方法和Demo,均來自三方庫KJCategories,如有需要的朋友可自行pod 'KJCategories'引入即可

自定義文本顯示位置介紹就到此完畢,后面有相關(guān)再補充,寫文章不容易,還請點個小星星傳送門

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容