一、需求图如下所示
- UILabel 的高度自适应
- UILabel中的段落间距可设置
图片效果如下:
调整段落适应长宽高方式:
需求:
保证“游戏玩法” 章节,UILabel高度自适应,行内距为4px
做法:
UILabel实现自适应宽高(一)中说明了 UILabel 自适应的方法,但是如果加行间距,就要用到 NSMutableAttributedString 富文本的方式实现,来判断行内距然后再通过 sizetofit 进行高度自适应。
自适应方法如下:
Coding:
- (void)setLineSpacing:(CGFloat)spacing label:(UILabel *)label
{
if(!label.text.length) return;
NSMutableAttributedString *attributedString = [[NSMutableAttributedStringalloc] initWithString:label.text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStylealloc] init];
[paragraphStyle setLineSpacing:spacing];
[attributedString addAttribute:NSParagraphStyleAttributeNamevalue:paragraphStyle range:NSMakeRange(0, [label.textlength])];
[label setAttributedText:attributedString];
label.lineBreakMode = NSLineBreakByCharWrapping;
[label sizeToFit];
}
{
if(!label.text.length) return;
NSMutableAttributedString *attributedString = [[NSMutableAttributedStringalloc] initWithString:label.text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStylealloc] init];
[paragraphStyle setLineSpacing:spacing];
[attributedString addAttribute:NSParagraphStyleAttributeNamevalue:paragraphStyle range:NSMakeRange(0, [label.textlength])];
[label setAttributedText:attributedString];
label.lineBreakMode = NSLineBreakByCharWrapping;
[label sizeToFit];
}
注意一下label.lineBreakMode = NSLineBreakByCharWrapping;这句话一定要在UILabel设置富文本之后加,不然会不起作用。
sizeToFit 自适应方法也要在最后加,不然会被富文本方法替换掉。
二、需求图如下所示
- UILabel 中如果为数字,会显示红色
图片效果如下:
做法: 通过UILabel的富文本来实现此方法,遍历UILabel文本中如果有数字,自动设置为红色.
实现:
NSMutableString * subtitlelabelStr=[NSMutableStringstringWithFormat:@"共参与%ld期,%@", _dataModel.count,_dataModel.last_time];
_subtitlelabel.text = subtitlelabelStr;
NSString *content = subtitlelabelStr;
NSArray *number = @[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9"];
NSMutableAttributedString *attributeString = [[NSMutableAttributedStringalloc]initWithString:content];
for (int i = 0; i < content.length; i ++) {
NSString *a = [content substringWithRange:NSMakeRange(i, 1)];
if ([number containsObject:a]) {
[attributeString setAttributes:@{NSForegroundColorAttributeName:NF_Color_C19,NSFontAttributeName:[UIFontsystemFontOfSize:Near_Final_Font_T9]}range:NSMakeRange(i, 1)];
}
}
_subtitlelabel.attributedText = attributeString;
_subtitlelabel.text = subtitlelabelStr;
NSString *content = subtitlelabelStr;
NSArray *number = @[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9"];
NSMutableAttributedString *attributeString = [[NSMutableAttributedStringalloc]initWithString:content];
for (int i = 0; i < content.length; i ++) {
NSString *a = [content substringWithRange:NSMakeRange(i, 1)];
if ([number containsObject:a]) {
[attributeString setAttributes:@{NSForegroundColorAttributeName:NF_Color_C19,NSFontAttributeName:[UIFontsystemFontOfSize:Near_Final_Font_T9]}range:NSMakeRange(i, 1)];
}
}
_subtitlelabel.attributedText = attributeString;
问题:如果实现UIlabel 内容的文字全部为随机颜色,如何实现?