iOS swift Label富文本改变部分文字大小颜色

func attributedtext(text:String,mainColor:UIColor,mainFont:CGFloat,mainText:String,subColor:UIColor,subfont:CGFloat,subText:String) ->NSMutableAttributedString{

       let attrstring:NSMutableAttributedString = NSMutableAttributedString(string:text)

       let str =NSString(string: text)

      let theRange = str.range(of: mainText)

       attrstring.addAttribute(NSAttributedString.Key.foregroundColor, value: mainColor, range: theRange)

       attrstring.addAttribute(NSAttributedString.Key.font, value:UIFont.systemFont(ofSize: mainFont), range: theRange)

       let theSubRange = str.range(of: subText)

       attrstring.addAttribute(NSAttributedString.Key.foregroundColor, value: subColor, range: theSubRange)

       attrstring.addAttribute(NSAttributedString.Key.font, value:UIFont.systemFont(ofSize: subfont), range: theSubRange)

      return attrstring

   }

使用方法

label.attributedText=attributedtext(text:"1234567890", mainColor:color_333333, mainFont:12, mainText:"12345,", subColor:color_fb464c, subfont:12, subText:"67890")

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。