您好,欢迎来到伴沃教育。
搜索
您的当前位置:首页Swift中Label显示富文本或HTML

Swift中Label显示富文本或HTML

来源:伴沃教育

Label中显示自定义颜色或者大小的方式

//富文本设置
        var attributeString = NSMutableAttributedString(string:"welcome to 
        //从文本0开始6个字符字体HelveticaNeue-Bold,16号
        attributeString.addAttribute(NSFontAttributeName, value: UIFont(name: "HelveticaNeue-Bold", size: 16)!,
            range: NSMakeRange(0,6))
        //设置字体颜色
        attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueColor(),
            range: NSMakeRange(0, 3))
        //设置文字背景颜色
        attributeString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.greenColor(),
            range: NSMakeRange(3,3))

msgLabel.attributedText = attributeString

显示HTML

var htmlText = "空は<font color=\"blue\">青い</font>。<br>An apple is <font color=\"red\">red</font>."
        do{
            let attrStr = try NSAttributedString(data: htmlText.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)

            msgLabel.attributedText = attrStr
        }catch let error as NSError {
            print(error.localizedDescription)
        }

这里不懂为什么要加上do...catch

Copyright © 2019- bangwoyixia.com 版权所有 湘ICP备2023022004号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务