How do I get a custom text equivalent of an NSAttributedString containing a UIImage?

I have a chat application where I need to send images (emoticons) along with text.
Now I can add an image via NSTextAttatchment

(below code)

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;

      

Now I want custom text to add " :)

" to the smile icon so that when called, it _txtChat.text

returns :) instead UIImage

. So if the user sees Hii <Smilie>

, I would get "Hii :)"

. I can't figure out if this can be done.

+3


source to share


1 answer


I got the solution myself. We need to do the following: -
1. To get the content, we need to add a method (richText) to the UITextView (customCategory), for example UITextView (RichText) (the text is already there, so I recommend richText) to get the desired text values.
2. Save your own text in the NSTextAttachment. This was done by subclassing NSTextAttachment (in customNSTextAttatchment) and adding a custom @property id.

Now, after creating a customNSTextAttachment (similar to the code in my question), we can assign our desired NSString to custom.

To get it, we do the following:



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

      

}

+3


source







All Articles