富文本
NSString*str =@"人生若只如初见,何事秋风悲画扇。\n等闲变却故人心,却道故人心易变。\n骊山语罢清宵半,泪雨霖铃终不怨。\n何如薄幸锦衣郎,比翼连枝当日愿。";NSMutableAttributedString*attrStr = [[NSMutableAttributedStringalloc] initWithString:str];
attrStr添加字体和设置字体的范围
[attrStraddAttribute:NSFontAttributeName value:[UIFontsystemFontOfSize:30.0f] range:NSMakeRange(0,3)];
attrStr添加文字颜色
[attrStraddAttribute:NSForegroundColorAttributeName value:[UIColorredColor] range:NSMakeRange(17,7)];
attrStr添加下划线
[attrStr addAttribute:NSUnderlineStyleAttributeNamevalue:[NSNumbernumberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(8,7)];
段落样式
NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];//行间距paragraph.lineSpacing =10;//段落间距paragraph.paragraphSpacing =20;//对齐方式paragraph.alignment = NSTextAlignmentLeft;//指定段落开始的缩进像素paragraph.firstLineHeadIndent =30;//调整全部文字的缩进像素paragraph.headIndent =10;
attrStr添加段落设置
[attrStr addAttribute:NSParagraphStyleAttributeNamevalue:paragraph range:NSMakeRange(0, [str length])];NSString*urlStr =@"www.南瓜瓜.com";NSURL*url = [NSURLURLWithString:urlStr];
label添加链接
注意:label链接是可以显示出来,但是点不了,有兴趣的朋友可以试试。查资料发现textView是可以点击的,有shouldInteractWithURL代理方法回调。
[attrStraddAttribute:NSLinkAttributeName value:url range:NSMakeRange(42,7)];
创建label
UILabel*label = [[UILabelalloc] initWithFrame:CGRectMake(60,100,200,0)];label.backgroundColor= [UIColorlightGrayColor];//自动换行label.numberOfLines=0;//设置label的富文本label.attributedText= attrStr;//label高度自适应[label sizeToFit];[self.viewaddSubview:label];
设置sizeToFit之后是可以取出label的高度的,这样做label高度自适应。
CGFloatheight = label.frame.size.height;NSLog(@"height = %f",height);