UITextView与NSAttributedString和自定义属性不工作 [英] UITextView with NSAttributedString and custom attributes not working

查看:503
本文介绍了UITextView与NSAttributedString和自定义属性不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用UITextView时,我尝试向属性字符串添加自定义属性。但是,所有自定义键都会在分配给UITextView的attributedText后丢失。像这样:

  NSMutableAttributedString * lString = [[NSMutableAttributedString alloc] initWithString:@astring
attributes:@ { @customkey:@customvalue}];
NSLog(@string:%@,lString); //显示customkey present
textView.attributedText = lString;
NSLog(@result:%@,self.textView.attributedText); //显示自定义键缺失

这是否正常?

解决方案

基于这些意见,你试图滥用 NSAttributedString NSAttributedString UITextView 仅用于处理记录的属性。您可能最初可以在字符串中存储自定义属性,但是一旦文本视图开始处理属性文本,并且要求文本视图获取最新的属性文本,文本视图将很快被删除任何自定义属性。 p>

更好的解决方案是创建一个扩展UITextView的类。你的子类应该添加一个属性,可以容纳你想要的任何自定义属性。或者你的自定义类将覆盖 attributText 和'setAttributedText:`方法。



注意:此答案适用于iOS 6及更早版本
对于iOS 7,请参见下面的@ julien_c的回答。


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?

解决方案

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.

这篇关于UITextView与NSAttributedString和自定义属性不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆