ios - 使用 UITextView 在 NSAttributedString 中自动调整图像大小

标签 ios swift uitextview nsattributedstring

我试图让 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/

相关文章:

iphone - 如何在 iPhone iOS 5.0 中禁用表情符号键盘

ios - 如何使用 UISaveVideoAtPathToSavedPhotosAlbum 保存 youtube 视频?

ios - 将存档发送到 App Store Connect 时出错

设置 setVisibleXRangeMaximum 时,iOS-Charts X 轴值无限重复

ios - 逐字读取 UITextView

ios - UITextView 替代方案

iphone - 如何在 UI 自动化(iPhone)中访问第二页的元素?

swift - 在其下标 getter 中改变结构

ios - 如何使用 Sqlite.swift 获取列名列表?

ios - 如何从点击位置获取 UITextView 中文本的范围值?