我想知道Venmo如何放置自定義圖釋到他們的文本字段。自定義圖像的UITextField像Venmo應用
當你複製這些圖像,並將它們粘貼到其他地方,他們顯示爲「:夕陽」,「:演唱會:」等
所以我的想法是相匹配的任何文本的文本字段委託檢查模式(即「:演唱會:」),並用一個小圖像替換它。
所以我想知道你怎麼能一個文本框與其他文字中把自己的小的UIImageView。
編輯:這也可能是一個UITextView現在,我想它
我想知道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://stackoverflow.com/a/38016657/5442445)。 – beyowulf
@beyowulf這是有幫助的 - 我有它工作的UILabel和UITextView的,但圖像不會顯示的UITextField。我會進一步探索,但現在這個工作。謝謝! – vikzilla
@vikzilla那** **是最有可能是'UITextView',因爲'UITextField'不支持富文本。 – xoudini