3

我有一个聊天应用程序,我需要在其中发送图像(表情符号)和文本。
现在,我可以通过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 :)"。我无法确定是否有可能获得。

4

1 回答 1

3

自己得到了解决方案。我们需要执行以下操作:-
1. 要检索内容,我们需要向 UITextView(customCategory) 添加一个方法 (richText) 说 UITextView(RichText) (文本已经存在,所以我推荐richText)以检索所需文本值。
2. 将自定义文本保存到 NSTextAttachment 中。这是通过将 NSTextAttachment 子类化(到 customNSTextAttatchment 中)并添加一个 @property id 自定义来完成的。

现在,在创建 customNSTextAttachment(类似于我的问题中的代码)之后,我们可以将所需的 NSString 分配给 custom.

要检索,我们执行以下操作:

@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;

}

于 2014-12-10T13:33:55.167 回答