UITextView with NSAttributedString and custom attributes not working

When using a UITextView, I am trying to add a custom attribute to an attribute string. However, all user keys are lost after the UITextView attribittedText is assigned. Like this:

NSMutableAttributedString *lString = [[ NSMutableAttributedString alloc ] initWithString: @"astring" attributes: @{ @"customkey": @"customvalue" }]; NSLog(@"string: %@", lString); // shows customkey present textView.attributedText = lString; NSLog(@"result: %@", self.textView.attributedText); // shows customkey missing 

Should it work?

+6
source share
3 answers

Based on the comments, you are trying to use NSAttributedString . NSAttributedString and UITextView are only for handling documented attributes. You can first save the user attributes in a string, but as soon as the text view starts processing the sent text, and you ask for the text view for the last attribute of the text, the text view will get rid of any user attributes for a long time.

A better solution would be to create a class extending the UITextView. Your subclass should add a property that can contain any custom attributes. Or maybe your custom class will override the attributedText and setAttributedText: methods. They will take care of saving and restoring any custom attributes found in the attribute string.

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

+5
source

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

From Attribute Access :

An assigned string identifies attributes by name, storing the value under the attribute name in an NSDictionary object, which in turn is associated with NSRange, which indicates the characters to which dictionary attributes are applied. In addition to the standard attributes, you can assign a pair of name-value attributes that you want next to the characters.

It works with both standard and NSTextStorage (text set) with support for UITextViews.

+16
source

UITextView does not really display attribute strings. Apple has an inner class NSHTMLWriter that converts the NSAttributedString to HTML data, which is then displayed by the contents of the UIWebDocumentView (which is essentially Webkit)

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

+3
source

All Articles