Swift富文本

字符串中单个变色

extension String {
 public func getAttributedString(sender:String) -> NSMutableAttributedString {
        
        let attributedString = NSMutableAttributedString.init()
        
        let jndex   = self.range(of: sender)
        let before = self.substring(to: (jndex?.lowerBound)!)
        
        let beforeAttributedString = NSAttributedString.init(string: before, attributes: [NSFontAttributeName:UIFont.boldSystemFont(ofSize: 16),NSForegroundColorAttributeName:UIColor.black])
        attributedString.append(beforeAttributedString)
        
        let titleAttributedString = NSAttributedString.init(string: sender, attributes: [NSForegroundColorAttributeName:UIColor.cyan,NSFontAttributeName:UIFont.boldSystemFont(ofSize: 16)])
        attributedString.append(titleAttributedString)
        
        let upper = self.substring(from: (jndex?.upperBound)!)
        
        let contentAttributedString = NSAttributedString.init(string: upper, attributes: [NSFontAttributeName:UIFont.boldSystemFont(ofSize: 16),NSForegroundColorAttributeName:UIColor.black])
        
        attributedString.append(contentAttributedString)
        return attributedString
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 这一篇我们将实现一个富文本编辑器,拥有功能: 1、斜体、下划线混排。 2、图文混排 3、字体大小。 4、选择自定义...
    StrongX阅读 13,475评论 14 51
  • 如果需要一个字符前后文字颜色不一样,也就是说一个字符串分成多个部分,每个部分的属性(颜色,字体,大小等)不一样,...
    Bart_Simpson阅读 9,159评论 0 4
  • 最近在做一个练习项目的时候,经常写到要设置富文本属性的地方,所以写了一个简单的封装,因为swift的字符下标采用的...
    figure_ai阅读 894评论 1 4
  • 周末闲着无聊,想起最近遇到一个关于文字显示设置的小问题,想着以后可能还会经常用到,所以趁这个时候一起整理一下,方便...
    figure_ai阅读 10,989评论 0 5
  • 一,在界面放一个label 二,设置富文本文字 三,从文本23开始4个字符字体HelveticaNeue-Bold...
    _杜兜兜_阅读 578评论 0 0