UITextView with NSAttributedString and custom attributes not working

十年热恋 提交于 2019-12-09 06:04:08

问题


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?


回答1:


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.




回答2:


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.




回答3:


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/



来源:https://stackoverflow.com/questions/13648003/uitextview-with-nsattributedstring-and-custom-attributes-not-working

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