UITextView显示WordPress文章HTML图片仅部分显示问题求助
解决UITextView展示HTML图片只显示一部分的问题
我之前踩过一模一样的坑!当用NSAttributedString把WordPress的HTML内容转成富文本后,UITextView里的图片只显示半截,核心原因是HTML转富文本时,图片会保留原始尺寸,如果原图宽度超过UITextView的可视宽度,就会被容器截断。下面给你两种靠谱的解决思路:
方法一:手动遍历并调整图片附件尺寸(最可靠)
这种方法直接操作富文本里的图片附件,按UITextView的宽度等比例缩放,适配性最强,不受iOS版本差异影响。
先写一个工具方法来处理富文本:
func resizeImagesInAttributedString(_ attributedString: NSAttributedString, toWidth targetWidth: CGFloat) -> NSAttributedString { let mutableAttrStr = NSMutableAttributedString(attributedString: attributedString) // 遍历所有图片附件 mutableAttrStr.enumerateAttribute(.attachment, in: NSRange(location: 0, length: mutableAttrStr.length)) { (value, range, _) in guard let attachment = value as? NSTextAttachment, let originalImage = attachment.image else { return } // 计算缩放比例:只缩小不放大,保持宽高比 let scale = min(targetWidth / originalImage.size.width, 1.0) let newSize = CGSize(width: originalImage.size.width * scale, height: originalImage.size.height * scale) // 更新附件的bounds let newAttachment = NSTextAttachment() newAttachment.image = originalImage newAttachment.bounds = CGRect(origin: .zero, size: newSize) // 替换原附件 mutableAttrStr.addAttribute(.attachment, value: newAttachment, range: range) } return mutableAttrStr }
然后在你的业务代码里这样用:
// 假设yourHTMLContent是从接口拿到的HTML字符串 guard let htmlString = yourHTMLContent else { return } // 1. 先把HTML转成基础富文本 guard let baseAttrStr = NSAttributedString(html: htmlString) else { return } // 2. 计算UITextView的可用宽度(减去左右内边距) let availableWidth = textView.bounds.width - textView.contentInset.left - textView.contentInset.right // 3. 调整图片尺寸后赋值给UITextView let resizedAttrStr = resizeImagesInAttributedString(baseAttrStr, toWidth: availableWidth) textView.attributedText = resizedAttrStr
方法二:转换HTML时指定文档宽度(更简洁)
你也可以在初始化NSAttributedString时,通过设置文档属性来让系统自动适配宽度,不过这个方法在部分iOS版本上对图片的处理可能不够稳定:
先修改你的NSAttributedString扩展:
extension NSAttributedString { convenience init?(html: String, preferredWidth: CGFloat? = nil) { guard let data = html.data(using: .utf8, allowLossyConversion: false) else { return nil } var options: [NSAttributedString.DocumentReadingOptionKey: Any] = [ .documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue ] // 如果传入了目标宽度,设置文档尺寸约束 if let width = preferredWidth { options[.documentSize] = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude) } do { try self.init(data: data, options: options, documentAttributes: nil) } catch { print("HTML转富文本失败:\(error)") return nil } } }
使用时直接传入UITextView的可用宽度:
let availableWidth = textView.bounds.width - textView.contentInset.left - textView.contentInset.right if let attrStr = NSAttributedString(html: yourHTMLContent, preferredWidth: availableWidth) { textView.attributedText = attrStr }
额外注意点
- 确保UITextView的
isScrollEnabled设为true,不然高度不够时图片可能还是显示不全; - 如果你的HTML里有带样式的图片(比如inline样式设置了宽度),优先以HTML里的样式为准,但上面的方法还是能覆盖调整;
内容的提问来源于stack exchange,提问作者Mercadeo Web
相关产品推荐
相关产品推荐

