我试图让 UITextView
显示带有图像的 rtfd 文档。问题是,图像与 UITextView
的框架重叠 - 它具有更大的宽度。我需要将此图像缩放到 UITextView
的宽度。这是我加载字符串的方式:
if let text = try? NSMutableAttributedString(URL: NSBundle.mainBundle().URLForResource("License agreement", withExtension: "rtfd")!, options: [NSDocumentTypeDocumentAttribute : NSRTFDTextDocumentType], documentAttributes: nil) {
textView.attributedText = text
}
我也尝试使用 img style="width: 100%"
的 webarchive 文件,但这也没有用。
以这种方式显示 rtfd 或其他文档的最佳方式是什么,以便缩放图像以适应宽度?
最佳答案
谢谢 Larme 的评论,我设法让它像这样工作:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
prepareTextImages()
}
private var text: NSMutableAttributedString?
private func prepareTextImages() {
let width = CGRectGetWidth(self.view.frame) - self.containerView.frame.origin.x * 2 - 10
text?.enumerateAttribute(NSAttachmentAttributeName, inRange: NSRange(location: 0, length: text!.length), options: [], usingBlock: { [width] (object, range, pointer) in
let textViewAsAny: Any = self.textView
if let attachment = object as? NSTextAttachment, let img = attachment.imageForBounds(self.textView.bounds, textContainer: textViewAsAny as? NSTextContainer, characterIndex: range.location) {
if attachment.fileType == "public.png" {
let aspect = img.size.width / img.size.height
if img.size.width <= width {
attachment.bounds = CGRect(x: 0, y: 0, width: img.size.width, height: img.size.height)
return
}
let height = width / aspect
attachment.bounds = CGRect(x: 0, y: 0, width: width, height: height)
}
}
})
}
这有一个小问题 - 滚动时,我在查看此图像时看到一个小延迟。在不改变尺寸的情况下,全尺寸图像不会发生这种情况。有人能想出其中的原因吗?
关于ios - 使用 UITextView 在 NSAttributedString 中自动调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36372042/