iOS富文本,自定义的string

 首先:如果可以使用第三方的话可以看看YYKit   特别好的一个库

 贴一下地址:http://www.oschina.net/p/yykit?fromerr=0QjGntqH

 

我的项目中是无法使用第三方的,下面是我自己用NSMutableAttributedString实现该功能的代码.

NSString *critics = [NSString stringWithString: commentModel.critics];//评论人
    NSString *commentContent = [NSString stringWithString:commentModel.commentContent];//评论内容
    NSString *byCritics = [NSString stringWithString:commentModel.byCritics];//被回复的人
    if ([byCritics isEqualToString:@""])
    {
        
        NSString *listStr = [NSString stringWithFormat:@"%@:%@",critics,commentContent];
        
        NSRange trueNameRange = [listStr rangeOfString:critics];
        
        NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:listStr];
        
        [AttributedStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0] range:trueNameRange];
        
        [AttributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:trueNameRange];
        
        self.commentLabel.attributedText = AttributedStr;
    }
    else
    {
        
    NSString *listStr = [NSString stringWithFormat:@"%@回复%@:%@",critics,byCritics,commentContent];
    /*
      一开始这样取range  并不能得到想要的结果
     */
//    NSRange trueNameRange = [listStr rangeOfString:critics];
//    NSRange positionRange = [listStr rangeOfString:byCritics];
    
    NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:listStr];
    
    
    [AttributedStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0] range:NSMakeRange(0, critics.length)];
    [AttributedStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0] range:NSMakeRange(critics.length + 2, byCritics.length)];
    
    [AttributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, critics.length)];
    [AttributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(critics.length + 2, byCritics.length)];

    
    self.commentLabel.attributedText = AttributedStr;
        
    }

这样 label上显示的字符串就变成了一个有颜色的字符串.字体大小不同的字符串.当然还可以加一些别的效果.有用到的再深入研究.

转载于:https://my.oschina.net/u/2555813/blog/726705

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值