项目中遇到后台返回的html字符串,需要解析.最后发现只要用系统的UILabel和UITextView就可以实现.但是除了解析我们还需要监听图片点击放大.label 就不合适了.然后决定选用textView.很简单的就解析了.但是最后碰到难点就是如何监听其中的图片对象点击.刚开始想着是遍历字符串然后找到图片对象添加点击事件,发现异常繁琐.最后终于找到 了textfield有代理方法可以直接监听,废话不说,上代码.最后用MJ的图片浏览器展示即可.搞定收工!
SDRichTextView *textView = [[SDRichTextView alloc] init];
textView.backgroundColor = [UIColor clearColor];
textView.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);
textView.frame = CGRectMake(12, 16, KScreenW - 2 * 12, 100);
textView.attributedText = attributedString;
textView.font = [UIFont systemFontOfSize:15];
textView.delegate = self;
textView.editable = NO; //必须禁止输入,否则点击将弹出输入键盘
textView.scrollEnabled = NO;
[textView sizeToFit];
[headView addSubview:textView];
// 监听文本附件点击
- (BOOL)textView:(UITextView *)textView shouldInteractWithTextAttachment:(NSTextAttachment *)textAttachment inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction
{
//NSLog(@"Attachment:%@, characterRange:%@",textAttachment,NSStringFromRange(characterRange));
//NSFileWrapper
UIImage *image = [UIImage imageWithData:textAttachment.fileWrapper.regularFileContents];
// NSString *url = [textAttachment.fileWrapper.symbolicLinkDestinationURL absoluteString];
// NSLog(@"url:%@",url);
if (image && image.classForCoder == [UIImage class]) {
//NSLog(@"image:%@",image);
// 显示照片
MJPhoto *photo = [[MJPhoto alloc] init];
photo.currentIndexItem = 1;
photo.toolBarType = MJToolBarTypeShowPhotoBrowser;
photo.image = image;
// 显示相册
MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
browser.currentPhotoIndex = 0; // 弹出相册时显示的第一张图片
browser.photos = @[photo]; // 设置所有的图片
[browser show];
}
return YES;
}