专注iOS开发iOS Developer傲视苍穹iOS《Objective-C》VIP专题

设置UILabel行间距最简单的方式

2016-10-17  本文已影响492人  Pr_Chen

一般情况下,通过段落样式和属性文本即可设置标签的行间距。

例如:

UILabel *label = [UILabel new];

NSString *string = @"如何让你遇见我,在我最美丽的时刻。为这,我已在佛前求了五百年,求他让我们结一段尘缘";。

NSMutableParagraphStyle *style = [NSMutableParagraphStyle new];
style.lineSpacing = 10;
style.lineBreakMode = NSLineBreakByTruncatingTail;

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string];
[attrString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, string.length)];
label.attributedText = attrString;

项目中经常会有调整行间距的地方,应尽可能的复用代码。故有几种方式:

  1. 新建UILabel的子类,增加 行间距 属性。
  2. 新建UILabel的子类,新增设置文本的方法,例如- (void)setText:(NSString *)text lineSpacing:(CGFloat)lineSpacing;
  3. 为UILabel增加分类,增加设置行间距的属性。
  4. 为UILabel增加分类,增加设置行间距的方法。

第三种方式对代码的侵入性最小,耦合性最低,使用最为自然,故最为适宜。通过runtime将原有的setText:方法实现替换成带有行间距的方式,可以做到和使用系统API一样的体验。

.h文件内容

@interface UILabel (LineSpace)

//请不要将属性名称取为lineSpacing,UILabel已有此隐藏属性。
@property (assign, nonatomic) CGFloat lineSpace;

@end

.m文件内容

@implementation UILabel (LineSpace)

static char *lineSpaceKey;

+ (void)load {
    
    //交换设置文本的方法实现。
    Method oldMethod = class_getInstanceMethod([self class], @selector(setText:));
    Method newMethod = class_getInstanceMethod([self class], @selector(setHasLineSpaceText:));
    method_exchangeImplementations(oldMethod, newMethod);
}

//设置带有行间距的文本。
- (void)setHasLineSpaceText:(NSString *)text {
    
    if (!text.length || self.lineSpace==0) {
        [self setHasLineSpaceText:text];
        return;
    }
    
    NSMutableParagraphStyle *style = [NSMutableParagraphStyle new];
    style.lineSpacing = self.lineSpace;
    style.lineBreakMode = self.lineBreakMode;
    
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:text];
    [attrString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, text.length)];
    self.attributedText = attrString;
}

- (void)setLineSpace:(CGFloat)lineSpace {
    
    objc_setAssociatedObject(self, &lineSpaceKey, @(lineSpace), OBJC_ASSOCIATION_ASSIGN);
    self.text = self.text;
}

- (CGFloat)lineSpace {
    return [objc_getAssociatedObject(self, &lineSpaceKey) floatValue];
}

@end

若想支持在xib或者storyboard中设置行间距,请用IBInspectable宏修饰此属性即可。即:
@property (assign, nonatomic) IBInspectable CGFloat lineSpace;

上一篇下一篇

猜你喜欢

热点阅读