【问题标题】:How to add an image/button to a UITextView? With auto line break?如何将图像/按钮添加到 UITextView?自动换行?
【发布时间】:2011-06-13 23:49:07
【问题描述】:

我想向我的 UITextView 添加一个图像/按钮,并且文本应该自动换行以适合图像/按钮。

第二个问题。我想制作一个名为“移动图像/按钮”的按钮,然后用户可以通过 UITextView 移动图像/按钮,文本应为adjust

PS:就像 Mac 的“Pages”或 Windows 的“Word”

【问题讨论】:

    标签: iphone image button uitextview break


    【解决方案1】:

    这绝对不是微不足道的。对于初学者,您不能简单地将 UIImage 嵌入到 UITextView 中,即使您可以文本也不会神奇地围绕它流动。您需要做的是基于 UITextView 创建自己的对象,该对象大大扩展了其提供此类编辑工具的功能。

    要提前了解您正在了解的内容,您可能需要查看来自 Omni Group 的 example Text Editor source code

    【讨论】:

    • 好的,非常感谢您的帮助。 Mayby 这对我来说真的太多了。也许我可以找到其他解决方案。
    【解决方案2】:

    UITextViewattributedText 属性与NSAttributedStringNSTextAttachment 与图像一起使用。请注意,UITextView 必须是 Selectable(在 Storyboard 中)。

    Swift 演示:

    let attributedImage = NSAttributedString(with: #imageLiteral(resourceName: "myImage"))
    let attributedText = NSMutableAttributedString(string: "Hello ")
    attributedText.append(attributedImage)
    textView.attributedText = attributedText
    

    attributedImage 是从这些便利初始化器构建的:

    extension NSAttributedString {
        convenience init(with image: UIImage) {
            self.init(attachment: NSTextAttachment(with: image))
        }
    }
    extension NSTextAttachment {
        convenience init(with image: UIImage) {
            self.init()
            self.image = image
            // adjust origin if needed
            self.bounds = CGRect(origin: .zero, size: image.size)
        }
    }
    

    此解决方案适用于:iOS 7.0、macOS 10.11、tvOS 9.0、*。

    【讨论】:

      猜你喜欢
      • 2015-01-25
      • 2012-10-27
      • 2014-04-06
      • 2014-07-29
      • 1970-01-01
      • 2020-08-24
      相关资源
      最近更新 更多