iOS开发实战 - 轻松实现Label的全方位对齐

ARUILabelTextAlign
1. 实现 UILabel文本在 左(上 中 下)、中(上 中 下)、右(上 中 下) 9个方位显示;
2. 提供富文本底部不对齐的解决方案;
演示
核心代码:

ARAlignLabel.h

#import <UIKit/UIKit.h>
@class ARMaker;

typedef NS_ENUM(NSUInteger, textAlignType)
{
    textAlignType_top = 10,   // 顶部对齐
    textAlignType_left,       // 左边对齐
    textAlignType_bottom,     // 底部对齐
    textAlignType_right,      // 右边对齐
    textAlignType_center      // 水平/垂直对齐(默认中心对齐)
};

@interface ARAlignLabel : UILabel

/**
 *  根据对齐方式进行文本对齐
 *
 *  @param alignType 对齐block
 */
- (void)textAlign:(void(^)(ARMaker *make))alignType;

@end


//工具类
@interface ARMaker : NSObject

/* 存放对齐样式 */
@property(nonatomic, strong) NSMutableArray *typeArray;

/**
 *  添加对齐样式
 */
- (ARMaker *(^)(textAlignType type))addAlignType;

@end

ARAlignLabel.m

#import "ARAlignLabel.h"

@interface ARAlignLabel ()

/* 对齐方式 */
@property(nonatomic, strong) NSArray *typeArray;
//上
@property(nonatomic, assign) BOOL hasTop;
//左
@property(nonatomic, assign) BOOL hasLeft;
//下
@property(nonatomic, assign) BOOL hasBottom;
//右
@property(nonatomic, assign) BOOL hasRight;

@end

@implementation ARAlignLabel

- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
    CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
    if (self.typeArray){
        for (int i=0; i<self.typeArray.count; i++) {
            textAlignType type = [self.typeArray[i] integerValue];
            switch (type) {
                case textAlignType_top:  //顶部对齐
                    self.hasTop = YES;
                    textRect.origin.y = bounds.origin.y;
                    break;
                case textAlignType_left: //左部对齐
                    self.hasLeft = YES;
                    textRect.origin.x = bounds.origin.x;
                    break;
                case textAlignType_bottom: //底部对齐
                    self.hasBottom = YES;
                    textRect.origin.y = bounds.size.height - textRect.size.height;
                    break;
                case textAlignType_right: //右部对齐
                    self.hasRight = YES;
                    textRect.origin.x = bounds.size.width - textRect.size.width;
                    break;
                case textAlignType_center:
                    if (self.hasTop) {  //上中
                        textRect.origin.x = (bounds.size.width - textRect.size.width)*0.5;
                    }
                    else if (self.hasLeft) { //左中
                        textRect.origin.y = (bounds.size.height - textRect.size.height)*0.5;
                    }
                    else if (self.hasBottom) { //下中
                        textRect.origin.x = (bounds.size.width - textRect.size.width)*0.5;
                    }
                    else if (self.hasRight) { //右中
                        textRect.origin.y = (bounds.size.height - textRect.size.height)*0.5;
                    }
                    else{   //上下左右居中
                        textRect.origin.x = (bounds.size.width - textRect.size.width)*0.5;
                        textRect.origin.y = (bounds.size.height - textRect.size.height)*0.5;
                    }
                    break;
                default:
                    break;
            }
        }
    }
    return textRect;
}

- (void)drawTextInRect:(CGRect)requestedRect {
    CGRect actualRect = requestedRect;
    if (self.typeArray) {
        actualRect = [self textRectForBounds:requestedRect limitedToNumberOfLines:self.numberOfLines];
    }
    [super drawTextInRect:actualRect];
}

- (void)textAlign:(void(^)(ARMaker *make))alignType {
    ARMaker *make = [[ARMaker alloc]init];
    alignType(make);
    self.typeArray = make.typeArray;
}

@end

//工具类
@implementation ARMaker

- (instancetype)init {
    self = [super init];
    if (self) {
        self.typeArray = [NSMutableArray array];
    }
    return self;
}

- (ARMaker *(^)(enum textAlignType type))addAlignType {
    __weak typeof (self) weakSelf = self;
    return ^(enum textAlignType type) {
        [weakSelf.typeArray addObject:@(type)];
        return weakSelf;
    };
}

@end

工具使用 - 九个方位对齐
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    if (_index == 9) {
        //富文本底部对齐
        [self attributedTextAgainOfBottom];
    }else {
        ARAlignLabel *label = [[ARAlignLabel alloc] initWithFrame:CGRectMake(kScreenWidth/2.0 - 150, 300, 300, 80)];
        label.backgroundColor = [UIColor orangeColor];
        label.textColor = [UIColor blackColor];
        label.font = [UIFont systemFontOfSize:18];
        label.text = @"爱学习,爱编程,爱咖啡可乐";
        label.numberOfLines = 1;
        [self.view addSubview:label];
        
        switch (_index) {
            case 0:
                [label textAlign:^(ARMaker *make) {
                    make.addAlignType(textAlignType_left).addAlignType(textAlignType_top);
                }];
                break;
            case 1:
                [label textAlign:^(ARMaker *make) {
                    make.addAlignType(textAlignType_left).addAlignType(textAlignType_center);
                }];
                break;
            case 2:
                [label textAlign:^(ARMaker *make) {
                    make.addAlignType(textAlignType_left).addAlignType(textAlignType_bottom);
                }];
                break;
            case 3:
                [label textAlign:^(ARMaker *make) {
                    make.addAlignType(textAlignType_center).addAlignType(textAlignType_top);
                }];
                break;
            case 4:
                [label textAlign:^(ARMaker *make) {
                    make.addAlignType(textAlignType_center);
                }];
                break;
            case 5:
                [label textAlign:^(ARMaker *make) {
                    make.addAlignType(textAlignType_center).addAlignType(textAlignType_bottom);
                }];
                break;
            case 6:
                [label textAlign:^(ARMaker *make) {
                    make.addAlignType(textAlignType_right).addAlignType(textAlignType_top);
                }];
                break;
            case 7:
                [label textAlign:^(ARMaker *make) {
                    make.addAlignType(textAlignType_right).addAlignType(textAlignType_center);
                }];
                break;
            case 8:
                [label textAlign:^(ARMaker *make) {
                    make.addAlignType(textAlignType_right).addAlignType(textAlignType_bottom);
                }];
                break;
            default:
                break;
        }
    }
}
富文本底部对齐
//富文本底部对齐
- (void)attributedTextAgainOfBottom {
    
    CGFloat space = 10.0;
    
    ARAlignLabel *leftLB = [[ARAlignLabel alloc] initWithFrame:CGRectMake(20, 200, kScreenWidth/2.0 - 20 - space/2.0, 80)];
    leftLB.backgroundColor = [UIColor lightGrayColor];
    leftLB.textColor = [UIColor blackColor];
    leftLB.numberOfLines = 1;
    [self.view addSubview:leftLB];
    //右下
    [leftLB textAlign:^(ARMaker *make) {
        make.addAlignType(textAlignType_center);
    }];
    
    NSMutableAttributedString  *attributedArr = [[NSMutableAttributedString alloc] initWithString:@"单价 $123"];
    [attributedArr setAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:40], NSForegroundColorAttributeName:[UIColor blackColor]} range:NSMakeRange(0, 1)];
    [attributedArr setAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:25], NSForegroundColorAttributeName:[UIColor blackColor]} range:NSMakeRange(1, 1)];
    [attributedArr setAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20], NSForegroundColorAttributeName:[UIColor blueColor]} range:NSMakeRange(3, 1)];
    [attributedArr setAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:35], NSForegroundColorAttributeName:[UIColor redColor]} range:NSMakeRange(4, attributedArr.length - 4)];
    
    leftLB.attributedText = attributedArr;
    
    
    //对齐之后
    ARAlignLabel *rightLB = [[ARAlignLabel alloc] initWithFrame:CGRectMake(kScreenWidth/2.0 + space/2.0, 200, leftLB.frame.size.width, 80)];
    rightLB.backgroundColor = [UIColor lightGrayColor];
    rightLB.textColor = [UIColor blackColor];
    rightLB.numberOfLines = 1;
    [self.view addSubview:rightLB];
    //左下
    [rightLB textAlign:^(ARMaker *make) {
        make.addAlignType(textAlignType_center);
    }];
    
    //设置部分文字的偏移量 (0是让文字保持原来的位置, 负值是让文字下移,正值是让文字上移)
    [attributedArr addAttribute:NSBaselineOffsetAttributeName value:@(1) range:NSMakeRange(0, 1)];
    [attributedArr addAttribute:NSBaselineOffsetAttributeName value:@(0) range:NSMakeRange(1, 1)];
    [attributedArr addAttribute:NSBaselineOffsetAttributeName value:@(-2) range:NSMakeRange(3, 1)];
    [attributedArr addAttribute:NSBaselineOffsetAttributeName value:@(-3) range:NSMakeRange(4, attributedArr.length - 4)];
    
    rightLB.attributedText = attributedArr;
    
}

富文本底部对齐 - 使用场景:


Github:https://github.com/ArchLL/ARUILabelTextAlign

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,110评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,443评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,474评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,881评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,902评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,698评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,418评论 3 419
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,332评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,796评论 1 316
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,968评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,110评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,792评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,455评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,003评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,130评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,348评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,047评论 2 355

推荐阅读更多精彩内容