iOS:将underlineStyle属性添加到NSAttributedString,使文本视图消失

问题描述 投票:0回答:1

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

添加了字符串的属性。

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

然后文本视图消失。

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
    }
}
ios swift uitextfield nsattributedstring
1个回答
2
投票

试试这个属性

let attributes: [NSAttributedString.Key: Any] = [
    .underlineColor: underLineColor,
    .font: UIFont.systemFont(ofSize: 25),
    .underlineStyle: NSUnderlineStyle.thick.rawValue | NSUnderlineStyle.single.rawValue
]
© www.soinside.com 2019 - 2024. All rights reserved.