Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextView with NSAttributedString and custom attributes not working

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:

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

Is this supposed to work?

like image 604
Kristof Van Landschoot Avatar asked Nov 30 '12 15:11

Kristof Van Landschoot


1 Answers

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.

like image 104
julien_c Avatar answered Oct 05 '22 22:10

julien_c