背景:在實現textView的富文本時,如果添加一張圖片后,如果直接發送textView的內容時,圖片會被字符串“\U0000fffc”替換。
問題:如何刪除“\U0000fffc”字符串;如何替換textView中圖片的字符串;textView添加完圖片后,之前設置的textView的屬性被初始化了,怎么辦?
方法:
(1)對於第一個問題,百度到的答案如下:
NSString *codeString = @"\uFFFC"; NSString *msg=[msg stringByReplacingOccurrencesOfString:codeString withString:@""];
這個方法,試了之后,就可以的。
(2)基於textView的圖片替換,一個個人覺得比較合適的方式如下:
因為textView添加圖片時,用的是 NSTextAttachment 控件,所以,基於這個方法下, /**
將富文本轉換為帶有圖片標志的純文本
sysmbol: 是圖片的標志的字符串,例如:[圖片]
attributeString: 富文本字符串
*/
- (NSString *)textStringWithSymbol:(NSString *)symbol attributeString:(NSAttributedString *)attributeString{
NSString *string = attributeString.string;
//最終純文本
NSMutableString *textString = [NSMutableString stringWithString:string];
//替換下標的偏移量
__block NSUInteger base = 0;
//遍歷
[attributeString enumerateAttribute:NSAttachmentAttributeName inRange:NSMakeRange(0, attributeString.length)
options:0
usingBlock:^(id value, NSRange range, BOOL *stop) {
//檢查類型是否是自定義NSTextAttachment類
if (value && [value isKindOfClass:[NSTextAttachment class]]) {
//替換
[textString replaceCharactersInRange:NSMakeRange(range.location + base, range.length) withString:symbol];
//增加偏移量
base += (symbol.length - 1);
//將富文本中最終確認的照片取出來
NSTextAttachment *attachmentImg = (NSTextAttachment *)value;
[self.mutImgArray addObject:attachmentImg.image];
}
}];
return textString;
}
(3)textView添加完圖片后,之前設置的textView的屬性被初始化了。這個問題的意思是,如果textView的字體大小設置為18,顏色為紫色;添加完圖片后,textView的字體大小為14,字體顏色為黑色(textView自帶的效果);原因不詳,解決方法是,設置完圖片后,對textView的屬性重新設置。
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[self dismissViewControllerAnimated:YES completion:^{
UIImage * img = [info objectForKey:UIImagePickerControllerOriginalImage];
[self uploadPicture:img];
NSTextAttachment* textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = img;
textAttachment.bounds = CGRectMake(0, 0, self.view.frame.size.width - 28, [self getImgHeightWithImg:img]);
NSAttributedString* imageAttachment = [NSAttributedString attributedStringWithAttachment:textAttachment];
NSMutableAttributedString *attriStr = [_textView.attributedText mutableCopy];
[attriStr appendAttributedString:imageAttachment];
_textView.attributedText = attriStr;
//-------對textView的屬性重新設置
_textView.textColor = [UIColor purpleColor];
_textView.font = [UIFont systemFontOfSize:18];
}];
}
