2017-06-12 34 views
3

我想知道Venmo如何放置自定義圖釋到他們的文本字段。自定義圖像的UITextField像Venmo應用

當你複製這些圖像,並將它們粘貼到其他地方,他們顯示爲「:夕陽」,「:演唱會:」等

所以我的想法是相匹配的任何文本的文本字段委託檢查模式(即「:演唱會:」),並用一個小圖像替換它。

所以我想知道你怎麼能一個文本框與其他文字中把自己的小的UIImageView。

enter image description here

編輯:這也可能是一個UITextView現在,我想它

+1

使用'NSAttributedString'和'NSTextAttachment'像他們這樣做[這裏](https://stackoverflow.com/a/38016657/5442445)。 – beyowulf

+0

@beyowulf這是有幫助的 - 我有它工作的UILabel和UITextView的,但圖像不會顯示的UITextField。我會進一步探索,但現在這個工作。謝謝! – vikzilla

+0

@vikzilla那** **是最有可能是'UITextView',因爲'UITextField'不支持富文本。 – xoudini

回答

2

在截圖的文字輸入是幾乎可以肯定的UITextView自定義子類,在這裏我將介紹一種方法以此達到理想的效果。

這裏有一個簡短的演示,從一個UITextView複製到另一個包含自定義圖像文本:

Demonstration.

首先我們需要繼承NSTextAttachment手頭有圖像的文本表示,這我們稍後會在複製時使用。

class TextAttachment: NSTextAttachment { 
    var representation: String? 
} 

現在當我們創建一個包含圖像的屬性串,我們將添加圖像所需的文本形式的附件:

let attachment = TextAttachment() 
attachment.image = UIImage(named: "1f197") 
attachment.representation = ":anything-here:" 

接下來,我們將繼承UITextView和覆蓋copy(_:)方法UIResponderStandardEditActionsUITextView執行。

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 

顯然,這將是更直觀的文字轉換/繪文字/不管到附件在用戶正在輸入時即時進行。

+0

非常酷!我不知道你可以重寫複製/剪切/粘貼方法。我已經實現了在用戶輸入時將冒號內的文本轉換爲圖像的能力(如果該圖像名稱的資產存在),那麼我將把您的答案與我現在擁有的答案結合起來。謝謝! – vikzilla

+0

@vikzilla良好的,沒有問題! – xoudini