iOS:向 NSAttributedString 添加 underlineStyle 属性,使文本视图消失 [英] iOS: Adding underlineStyle attribute to NSAttributedString, makes the text view disappear

查看:109
本文介绍了iOS:向 NSAttributedString 添加 underlineStyle 属性,使文本视图消失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在故事板中创建了一个 UITextView.

I've create a UITextView in storyboard.

为字符串添加了属性.

一切顺利,直到我添加了 underlineStyle 属性.

All goes well, until I add underlineStyle attribute.

然后文本视图消失.

class ViewController: UIViewController {

    @IBOutlet weak var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let text = "random text <a href='http://www.google.com'>http://www.google.com </a> more random text"

        let attributedText = htmlStyleAttributeText(text: text)!

        let underLineColor: UIColor = UIColor(red: 245/255, green: 190/255, blue: 166/255, alpha: 1)

        let attributes: [NSAttributedString.Key: Any] = 
            [.underlineColor: underLineColor,
             .font: UIFont.systemFont(ofSize: 25),
             .underlineStyle: NSUnderlineStyle.thick] // Adding this makes the UITextView disappear. 

        let wholeRange = NSRange(attributedText.string.startIndex..., in: attributedText.string)
        attributedText.addAttributes(attributes, range: wholeRange)
        textView.attributedText = attributedText
    }

    public func htmlStyleAttributeText(text: String) -> NSMutableAttributedString? {

        if let htmlData = text.data(using: .utf8) {

            let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html, NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue]
            let attributedString = try? NSMutableAttributedString(data: htmlData, options: options, documentAttributes: nil)

            return attributedString
        }
        return nil
    }
}

推荐答案

试试这个属性

let attributes: [NSAttributedString.Key: Any] = [
    .underlineColor: underLineColor,
    .font: UIFont.systemFont(ofSize: 25),
    .underlineStyle: NSUnderlineStyle.thick.rawValue | NSUnderlineStyle.single.rawValue
]

这篇关于iOS:向 NSAttributedString 添加 underlineStyle 属性,使文本视图消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆