如何获取包含UIImage的NSAttributedString的自定义文本等效项?

问题描述 投票:3回答:1

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

ios objective-c nsattributedstring nsmutableattributedstring nstextattachment
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;

}

© www.soinside.com 2019 - 2024. All rights reserved.