NSMutableAttributedString-文本中添加图片

文本中添加图片 

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;

 

转载于:https://my.oschina.net/mexiaobai1315/blog/802039

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值