自定义图像的UITextField像Venmo应用
问题描述:
我想知道Venmo如何放置自定义图释到他们的文本字段。自定义图像的UITextField像Venmo应用
当你复制这些图像,并将它们粘贴到其他地方,他们显示为“:夕阳”,“:演唱会:”等
所以我的想法是相匹配的任何文本的文本字段委托检查模式(即“:演唱会:”),并用一个小图像替换它。
所以我想知道你怎么能一个文本框与其他文字中把自己的小的UIImageView。
编辑:这也可能是一个UITextView现在,我想它
答
在截图的文字输入是几乎可以肯定的UITextView
自定义子类,在这里我将介绍一种方法以此达到理想的效果。
这里有一个简短的演示,从一个UITextView
复制到另一个包含自定义图像文本:
首先我们需要继承NSTextAttachment
手头有图像的文本表示,这我们稍后会在复制时使用。
class TextAttachment: NSTextAttachment {
var representation: String?
}
现在当我们创建一个包含图像的属性串,我们将添加图像所需的文本形式的附件:
let attachment = TextAttachment()
attachment.image = UIImage(named: "1f197")
attachment.representation = ":anything-here:"
接下来,我们将继承UITextView
和覆盖copy(_:)
方法UIResponderStandardEditActions
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
显然,这将是更直观的文字转换/绘文字/不管到附件在用户正在输入时即时进行。
使用'NSAttributedString'和'NSTextAttachment'像他们这样做[这里](https://*.com/a/38016657/5442445)。 – beyowulf
@beyowulf这是有帮助的 - 我有它工作的UILabel和UITextView的,但图像不会显示的UITextField。我会进一步探索,但现在这个工作。谢谢! – vikzilla
@vikzilla那** **是最有可能是'UITextView',因为'UITextField'不支持富文本。 – xoudini