一般情況下,通過段落樣式和屬性文本即可設(shè)置標簽的行間距。
例如:
UILabel *label = [UILabel new];
NSString *string = @"如何讓你遇見我,在我最美麗的時刻。為這,我已在佛前求了五百年,求他讓我們結(jié)一段塵緣";。
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;
項目中經(jīng)常會有調(diào)整行間距的地方,應(yīng)盡可能的復(fù)用代碼。故有幾種方式:
- 新建UILabel的子類,增加 行間距 屬性。
- 新建UILabel的子類,新增設(shè)置文本的方法,例如
- (void)setText:(NSString *)text lineSpacing:(CGFloat)lineSpacing;。 - 為UILabel增加分類,增加設(shè)置行間距的屬性。
- 為UILabel增加分類,增加設(shè)置行間距的方法。
第三種方式對代碼的侵入性最小,耦合性最低,使用最為自然,故最為適宜。通過runtime將原有的setText:方法實現(xiàn)替換成帶有行間距的方式,可以做到和使用系統(tǒng)API一樣的體驗。
.h文件內(nèi)容
@interface UILabel (LineSpace)
//請不要將屬性名稱取為lineSpacing,UILabel已有此隱藏屬性。
@property (assign, nonatomic) CGFloat lineSpace;
@end
.m文件內(nèi)容
@implementation UILabel (LineSpace)
static char *lineSpaceKey;
+ (void)load {
//交換設(shè)置文本的方法實現(xiàn)。
Method oldMethod = class_getInstanceMethod([self class], @selector(setText:));
Method newMethod = class_getInstanceMethod([self class], @selector(setHasLineSpaceText:));
method_exchangeImplementations(oldMethod, newMethod);
}
//設(shè)置帶有行間距的文本。
- (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中設(shè)置行間距,請用IBInspectable宏修飾此屬性即可。即:
@property (assign, nonatomic) IBInspectable CGFloat lineSpace;