Reputation: 61
I have a chat application where I need to send Images(Emoticons) along with text.
Now, I can add image via NSTextAttachment
(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, what I want is to attach a custom text say ":)
" to the smile icon so that when calling _txtChat.text
would return :) instead of the UIImage
. So, If the user sees Hii <Smilie>
, I would get "Hii :)"
. I am unable to figure if it is possible to get.
Upvotes: 3
Views: 531
Reputation: 61
Got the solution myself.
We need to do the following :-
1. To retrieve the contents, we need to add a method (richText) to UITextView(customCategory) say UITextView(RichText) (text is already there so I recommend richText)in order to retrieve the desired text values.
2. Save the custom text into the NSTextAttachment. This was done by subclassing NSTextAttachment (into customNSTextAttatchment) and adding an @property id custom.
Now, after creation of customNSTextAttachment(similarly as the code in my question), we can assign our desired NSString into custom.
To retrieve, 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;
}
Upvotes: 3