文本中添加图片
NSAttributedString:可以设置文字的字体、颜色、下划线等一系列效果;
NSMutableAttributedString:功能和NSAttributedString类似,但是可以追加NSAttributedString,通过NSMutableAttributedString可以在文本中添加图片;
NSMutableAttributedString *mulStr = [[NSMutableAttributedString alloc] init];
//创建第一个文本
NSMutableDictionary *dic1 = [NSMutableDictionary dictionary];
dic1[NSForegroundColorAttributeName] = [UIColor greenColor];
NSAttributedString *str1 = [[NSAttributedString alloc] initWithString:@"你好" attributes:dic1];
//创建图片
NSTextAttachment *attach = [[NSTextAttachment alloc] init];
attach.image =[UIImage imageNamed:@"XXX.png"]; //设置图片
attach.bounds = CGRectMake(0, -7, 30, 30); //设置图片大小、位置
NSAttributedString *str2 = [NSAttributedString attributedStringWithAttachment:attach];
//创建第二个文本
NSMutableDictionary *dic3 = [NSMutableDictionary dictionary];
dic3[NSForegroundColorAttributeName] = [UIColor greenColor];
NSAttributedString *str3 = [[NSAttributedString alloc] initWithString:@"再见" attributes:dic1];
[mulStr appendAttributedString:str1];
[mulStr appendAttributedString:str2];
[mulStr appendAttributedString:str3];
UILabel *label = [[UILabel alloc] init];
label.textAlignment = NSTextAlignmentCenter;
label.backgroundColor = [UIColor redColor];
label.frame = CGRectMake(0, 0, 200, 44);
label.attributedText = mulStr; //将富文本添加到lable上
self.navigationItem.titleView = label;
文本换行显示
NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:@"123\nrwre"];
NSMutableDictionary *dic1 = [NSMutableDictionary dictionary];
dic1[NSForegroundColorAttributeName] = [UIColor greenColor];
[attStr setAttributes:dic1 range:NSMakeRange(0, 2)];
NSMutableDictionary *dic2 = [NSMutableDictionary dictionary];
dic2[NSForegroundColorAttributeName] = [UIColor greenColor];
[attStr setAttributes:dic2 range:NSMakeRange(4, 3)];
UILabel *label = [[UILabel alloc] init];
label.textAlignment = NSTextAlignmentCenter;
label.frame = CGRectMake(0, 0, 200, 80);
label.numberOfLines = 0;//设置label可以换行显示
label.attributedText = attStr;
self.navigationItem.titleView = label;