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