【发布时间】:2011-06-13 23:49:07
【问题描述】:
我想向我的 UITextView 添加一个图像/按钮,并且文本应该自动换行以适合图像/按钮。
第二个问题。我想制作一个名为“移动图像/按钮”的按钮,然后用户可以通过 UITextView 移动图像/按钮,文本应为adjust。
PS:就像 Mac 的“Pages”或 Windows 的“Word”
【问题讨论】:
标签: iphone image button uitextview break
我想向我的 UITextView 添加一个图像/按钮,并且文本应该自动换行以适合图像/按钮。
第二个问题。我想制作一个名为“移动图像/按钮”的按钮,然后用户可以通过 UITextView 移动图像/按钮,文本应为adjust。
PS:就像 Mac 的“Pages”或 Windows 的“Word”
【问题讨论】:
标签: iphone image button uitextview break
这绝对不是微不足道的。对于初学者,您不能简单地将 UIImage 嵌入到 UITextView 中,即使您可以文本也不会神奇地围绕它流动。您需要做的是基于 UITextView 创建自己的对象,该对象大大扩展了其提供此类编辑工具的功能。
要提前了解您正在了解的内容,您可能需要查看来自 Omni Group 的 example Text Editor source code。
【讨论】:
将UITextView 的attributedText 属性与NSAttributedString 与NSTextAttachment 与图像一起使用。请注意,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、*。
【讨论】: