UILabel设置不同的字体颜色或其他属性

1,通过attributedText设置,而且attributedText是可以append操作,这种可用于多个不同不行的text相连的操作,如下:

let scoretext = NSLocalizedString("my_score_title",comment:"")
        let textAttr = NSAttributedString(string: scoretext, attributes: nil)
        let scoreAttr = NSAttributedString(string: (data.score)!, attributes: [NSAttributedStringKey.foregroundColor:UIColor(255,  132, 41)])
        let mutattr = NSMutableAttributedString(attributedString: textAttr)
        mutattr.append(scoreAttr)
        myScoreLabel.attributedText = mutattr

2,一段文字中间某部分文字,设置不同的属性,这个是需要通过range来操作

//color and underline
        let dicattrs:Dictionary<NSAttributedStringKey,Any>=[NSAttributedStringKey.underlineStyle:0x01,NSAttributedStringKey.foregroundColor:UIColor(72,  199, 252)];
        termAndprivacyContent.addAttributes(dicattrs, range: nsRangeTerm!)
        termAndprivacyContent.addAttributes(dicattrs, range: nsRangePrivacy!)
        termprivacy.attributedText = termAndprivacyContent

3,文字+图片的样式

let text = (liveinfo.username)! + " "
        let attch = NSTextAttachment()
        if (liveinfo.gender)! == GenderType.male.rawValue{
            attch.image = #imageLiteral(resourceName: "male")
        }else{
            attch.image = #imageLiteral(resourceName: "female")
        }
        attch.bounds = CGRect(x:0,y:-2,width:32,height:32)
        let imageAttr = NSAttributedString.init(attachment: attch)
        let textAttr = NSAttributedString.init(string: text, attributes: nil)
        let mutattr = NSMutableAttributedString.init(attributedString: textAttr)
        mutattr.append(imageAttr)
        anchorNameLabel.attributedText = mutattr
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容