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. コンテンツを取得するには、メソッド (richText) を UITextView(customCategory) に追加する必要があります。たとえば、UITextView(RichText) (テキストは既に存在するため、richText をお勧めします) を取得します。テキスト値。
2. カスタム テキストを NSTextAttachment に保存します。これは、NSTextAttachment を (customNSTextAttachment に) サブクラス化し、@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;

}

于 2014-12-10T13:33:55.167 に答える