屏幕截图中的文本输入几乎肯定是UITextView 的自定义子类,这里我将介绍一种实现所需结果的方法。
这是一个简短的演示,将包含自定义图像的文本从一个 UITextView 复制到另一个:
首先,我们需要继承NSTextAttachment 以获得手头图像的文本表示,稍后我们将在复制时使用它。
class TextAttachment: NSTextAttachment {
var representation: String?
}
现在,当我们创建一个包含图像的属性字符串时,我们会将所需的图像文本表示添加到附件中:
let attachment = TextAttachment()
attachment.image = UIImage(named: "1f197")
attachment.representation = ":anything-here:"
接下来,我们将继承 UITextView 并覆盖 UIResponderStandardEditActions 中声明的 copy(_:) 方法,UITextView 实现了该方法。
class TextView: UITextView {
override func copy(_ sender: Any?) {
let selectedString = self.attributedText.attributedSubstring(from: self.selectedRange)
let enumeratableRange = NSRange(location: 0, length: selectedString.length)
let result = NSMutableAttributedString(attributedString: selectedString)
selectedString.enumerateAttribute(NSAttachmentAttributeName, in: enumeratableRange, options: []) { (value, range, _) in
if let attachment = value as? TextAttachment, let representation = attachment.representation {
result.replaceCharacters(in: range, with: representation)
}
}
UIPasteboard.general.string = result.string
}
}
我们还可以覆盖其他一些方法,例如 cut(_:) 和 paste(_:),但这超出了问题的范围。
最后,让我们将一些属性文本添加到自定义文本视图的实例中,看看它的实际执行情况:
var textView: TextView // Create an instance however.
let mutableString = NSMutableAttributedString()
mutableString.append(NSAttributedString(string: "Text with "))
mutableString.append(NSAttributedString(attachment: attachment))
mutableString.append(NSAttributedString(string: " text attachment."))
self.textView.attributedText = mutableString
显然,在用户键入时将文本/表情符号/任何内容即时转换为附件会更直观。