UITextView with NSAttributedString and custom attributes not working

后端 未结 3 814
粉色の甜心
粉色の甜心 2021-02-08 23:25

When using a UITextView I try to add a custom attribute to an attributed string. However, all custom keys are lost after assigning to a UITextView\'s attributedText. Like this:<

相关标签:
3条回答
  • 2021-02-08 23:49

    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.

    0 讨论(0)
  • 2021-02-08 23:58

    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.

    0 讨论(0)
  • 2021-02-09 00:06

    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/

    0 讨论(0)
提交回复
热议问题