我遇到了错误:
无法将类型为“ NSMutableAttributedString”的值分配为类型为“ String?”的
当尝试将字符串放入UITextView时。
我已阅读以下文章:https://www.hackingwithswift.com/articles/113/nsattributedstring-by-example,它指示NSAttributedString可与UITextView一起使用。我还尝试将NSMutuableAttributedString转换为String,如下所示:
self.text.text = String(attributedQuote)
但是,这没有用。
这会将“转录”分配为要转换为NSMutableAttributedString的字符串:
let attributedQuote = NSMutableAttributedString(string: transcription)
这为attributedQuote中的第一个单词添加了下划线:
attributedQuote.addAttribute(.underlineStyle, value: true, range: NSRange(location: 0, length: 4))
这会将attributedQuote添加到UITextView:
self.text.text = attributedQuote
不幸的是,当我期望第一个单词下划线时出现错误。
答案 0 :(得分:0)
感谢@rmaddy向我指出正确的方向。我在这里查看了文档:
https://developer.apple.com/documentation/uikit/uitextview/1618626-attributedtext
然后将我的代码相应地调整为:
self.text.attributedText = attributedQuote
我还发现以下帖子非常有用:
How do I make an attributed string using Swift?
我仍然遇到的一个问题是,当应用上述编码时,将重置textView的原始格式(居中对齐,字体大小,约束),因此我通过将适当的属性添加到attributedString中来重新调整了它们。有关更多信息,请参见本文:https://www.hackingwithswift.com/articles/113/nsattributedstring-by-example