Swift中Label显示富文本或HTML

2016-11-11  本文已影响1991人  King_Liu

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

//富文本设置
        var attributeString = NSMutableAttributedString(string:"welcome to hangge.com")
        //从文本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

上一篇 下一篇

猜你喜欢

热点阅读