iOS UITextView加载HTML内容时点击图片获取并全屏展示如何实现?
实现方案
预处理阶段:绑定图片附件与原始URL
你需要给系统的NSTextAttachment扩展一个自定义属性,用来存储对应图片的远程URL,实现方式用到runtime关联对象:
import ObjectiveC private var attachmentURLKey: UInt8 = 0 extension NSTextAttachment { /// 存储图片对应的原始远程URL var originalImageURL: String? { get { objc_getAssociatedObject(self, &attachmentURLKey) as? String } set { objc_setAssociatedObject(self, &attachmentURLKey, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) } } }
HTML加载完成后,按顺序给所有图片附件绑定URL:
- 先解析原始HTML字符串,提取所有
img标签的src属性,按出现顺序存入imageURLList数组 - 遍历生成的
NSAttributedString,按顺序取出所有NSTextAttachment实例,依次将imageURLList中的URL赋值给originalImageURL属性
点击事件阶段:获取对应URL并传递
你已经实现的点击拦截逻辑中,补充获取附件URL的逻辑即可:
@objc func textViewTapped(_ sender: UITapGestureRecognizer) { let touchPoint = sender.location(in: textView) // 获取点击位置对应的字符索引 guard let textPosition = textView.closestPosition(to: touchPoint), let charIndex = textView.offset(from: textView.beginningOfDocument, to: textPosition) as? Int, charIndex < textView.attributedText.length else { return } // 读取当前位置的文本附件 let attributes = textView.attributedText.attributes(at: charIndex, effectiveRange: nil) guard let attachment = attributes[.attachment] as? NSTextAttachment, let targetURL = attachment.originalImageURL else { return } // 初始化全屏图片控制器,传递URL即可 let fullImageVC = FullScreenPreviewController() fullImageVC.imageURL = URL(string: targetURL) present(fullImageVC, animated: true) }
可选优化
如果你的App已经实现了图片缓存逻辑,也可以直接把已加载的UIImage对象一起存在关联属性中,传递给新控制器时不需要二次加载,体验更好。
内容的提问来源于stack exchange,提问作者lucadb
相关产品推荐
相关产品推荐

