我有一个聊天应用程序,我需要在其中发送图像(表情符号)以及文本。
现在,我可以通过NSTextAttachment
添加图像(以下代码)
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
NSString *img=[NSString stringWithFormat:@"%@.png",imgName];
textAttachment.image =[UIImage imageNamed:img];
NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];
NSMutableAttributedString *nStr=[[NSMutableAttributedString alloc]initWithAttributedString:_txtChat.attributedText];
[nStr appendAttributedString:attrStringWithImage];
_txtChat.attributedText =nStr;
现在,我想要的是将自定义文本":)
"附加到微笑图标上,以便在呼叫时_txtChat.text
返回:)而不是UIImage
.所以,如果用户看到Hii <Smilie>
,我会得到"Hii :)"
。我无法弄清楚是否有可能得到。
自己得到了解决方案。我们需要执行以下操作:-
1.要检索内容,我们需要在UITextView(customCategory)中添加一个方法(富文本),比如UITextView(RichText)(文本已经存在,所以我推荐富文本)以检索所需的文本值。
2. 将自定义文本保存到 NSText附件中。这是通过子类化NSTextAttachment(到customNSTextAttatchment)并添加@property id custom来完成的。
现在,在创建customNSTextAttachment(类似于我问题中的代码)之后,我们可以将所需的NSString分配给自定义。
为了检索,我们执行以下操作:
@implementation UITextView(RichText)
-(NSString*)richText
{
__block NSString *str=self.attributedText.string; //Trivial String representation
__block NSMutableString *final=[NSMutableString new]; //To store customized text
[self.attributedText enumerateAttributesInRange:NSMakeRange(0, self.attributedText.length) options:0 usingBlock:
^(NSDictionary *attributes, NSRange range, BOOL *stop) {
//enumerate through the attributes
NSString *v;
NSObject* x=[attributes valueForKey:@"NSAttachment"];
if(x) //YES= This is an attachment
{
v=x.custom; // Get Custom value (i.e. the previously stored NSString).
if(v==nil) v=@"";
}
else v=[str substringWithRange:range]; //NO=This is a text block.
[final appendString:v]; //Append the value
}];
return final;
}