要在一个UITextView中既展示图片和文字,主要代码如下:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
//获得需要展示的图片
UIImage *image = info[UIImagePickerControllerEditedImage];
if (!image ) {
image = info[UIImagePickerControllerOriginalImage];
}
self.pictureImg = image;
//富文本添加文字、图片
NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithAttributedString:self.contentTV.attributedText];
[attri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:18] range:NSMakeRange(0, self.contentTV.text.length)];
//添加图片附件
NSTextAttachment *attch = [[NSTextAttachment alloc] init];
attch.image = image;
//大小需要根据图片去相应适配缩放比例;位置需要根据文字自适应高度
attch.bounds = CGRectMake(0, -5, ScreenWidth - 10,200);
NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
[attri appendAttributedString:string];
self.contentTV.attributedText = attri;
[picker dismissViewControllerAnimated:YES completion:nil];
}
使用
NSAttributedString属性来实现,这种适合上下来布局,并不适合图片上下左右被文字包围布局。