UITextView with NSAttributedString and custom attributes not working

允我心安 提交于 2019-12-03 07:11:46
rmaddy

Based on the comments, you are trying to misuse NSAttributedString.NSAttributedString and UITextView are only designed to handle the documented attributes. You may be able to initially store custom attributes in the string, but once the text view starts processing the attributed text and you ask the text view for the latest attributed text, the text view will have long gotten rid of any custom attributes.

The better solution would be to create a class that extends UITextView. Your subclass should add a property that can hold whatever custom attributes you want. Or maybe your custom class would override the attributedText and 'setAttributedText:` methods. These would take care of saving off and restoring any custom attributes found in the attributed string.

Note: this answer applies to iOS 6 and earlier. For iOS 7 see @julien_c's answer below.

Starting with iOS 7, it now works as you'd like:

From Accessing Attributes:

An attributed string identifies attributes by name, storing a value under the attribute name in an NSDictionary object, which is in turn associated with an NSRange that indicates the characters to which the dictionary’s attributes apply. You can assign any attribute name-value pair you wish to a range of characters, in addition to the standard attributes.

It works with both standard and NSTextStorage (Text Kit) backed UITextViews.

UITextView does not really display attributed strings. Apple has an internal class NSHTMLWriter which converts the set NSAttributedString into HTML data which is then displayed by the content UIWebDocumentView (which is essentially Webkit)

See my analysis here: http://www.cocoanetics.com/2012/12/uitextview-caught-with-trousers-down/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!