【问题标题】:Custom images in UITextField like Venmo appUITextField 中的自定义图像,如 Venmo 应用程序
【发布时间】:2017-06-12 14:40:08
【问题描述】:

我想知道 Venmo 如何将自定义表情符号放入他们的文本字段中。

当您复制这些图像并将它们粘贴到其他位置时,它们会显示为“:sunset:”、“:concert:”等。

所以我的猜测是 textField 委托会检查与该模式匹配的任何文本(即“:concert:”)并将其替换为一个小图像。

所以我想知道如何将自己的小 UIImageView 与其他文本一起放置在 textField 中。

编辑:现在我想这也可能是 UITextView

【问题讨论】:

  • 使用NSAttributedStringNSTextAttachment 就像他们使用here 一样。
  • @beyowulf 这很有帮助 - 我让它适用于 UILabel 和 UITextView,但图像不会显示在 UITextField 中。我将进一步探索,但这目前有效。谢谢!
  • @vikzilla 这很可能是UITextView,因为UITextField 不支持富文本。
  • @vikzilla 好吧,属性字符串基本上已经是富文本,但我在这种情况下的意思是“内联附件”,即图像。
  • @vikzilla 正如@xoudini 指出的那样,您可以覆盖默认的copy 实现。

标签: ios unicode uitextfield uitextview emoji


【解决方案1】:

屏幕截图中的文本输入几乎肯定是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

显然,在用户键入时将文本/表情符号/任何内容即时转换为附件会更直观。

【讨论】:

  • 非常酷!我不知道您可以覆盖复制/剪切/粘贴方法。我已经实现了在用户键入时将冒号内的文本转换为图像的功能(如果存在该图像名称的资产),因此我会将您的答案与我现在所拥有的结合起来。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-20
  • 1970-01-01
  • 2016-12-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多