- (void)changeLineSpaceForLabel:(UILabel *)label WithSpace:(float)space {
NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:label.text]
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]
[paragraphStyle setLineSpacing:space]
[attributedStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [label.text length])]
label.attributedText = attributedStr
[label sizeToFit]
}
//改变label的字间距
- (void)changeWordSpaceForLabel:(UILabel *)label WithSpace:(float)space {
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:label.text attributes:@{NSKernAttributeName:@(space)}]
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [label.text length])]
label.attributedText = attributedString
[label sizeToFit]
}
//改变行间距和字间距
- (void)changeSpaceForLabel:(UILabel *)label withLineSpace:(float)lineSpace WordSpace:(float)wordSpace {
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:label.text attributes:@{NSKernAttributeName:@(wordSpace)}]
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]
[paragraphStyle setLineSpacing:lineSpace]
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [label.text length])]
label.attributedText = attributedString
[label sizeToFit]
}
开发中遇到这样的需求,UILabel上对齐显示,指定行间距,末尾缩略,看似简单的需求,实现中踩了几个坑,记录下来,以备后用。
首先,想到的是用TTTAttributedLabel,上对齐和行间距可以完美解决,但是末尾缩略有问题,一行时正常缩略,多行时在最后一行都会加上省略号,放弃!
然后,UILabel本身没有属性设置上对齐,解决方案是自定义UILabel,在drawTextInRect中对对齐方式进行处理,上对齐的问题解决了,行间距的问题可以通过设置attributedText来解决。还剩一个缩略问题,这个地方有点坑,在UILabel初始化时设置lineBreakMode = NSLineBreakByTruncatingTail不起作用,需要在attributedText的paragraphStyle中设置才生效。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)