无法将图像作为NSTextAttachment添加到UITextField

时间:2019-02-21 10:26:57

标签: swift uitextfield nstextattachment

我正在尝试将图像作为NSTextAttachment添加到UITextField,但是我得到的只是,

自定义UITextField中的代码:

let myAttachment = NSTextAttachment()
myAttachment.image = myImage
myAttachment.bounds = CGRect(origin: .zero, size: myImage.size)

let myImageString = NSAttributedString(attachment: myAttachment)
let updatedText = NSMutableAttributedString()
updatedText.append(myImageString)

let myTextString = NSAttributedString(string: ", " + (self.text ?? ""))

updatedText.append(myTextString)

self.attributedText = updatedText

2 个答案:

答案 0 :(得分:1)

UITextField不允许NSTextAttachment,但UILabel允许NSTextAttachment

enter image description here

例如:

let attachment = NSTextAttachment()
let imageTest = UIImage(named:"user.png")
attachment.image = imageTest
let myString = NSMutableAttributedString(string: "My text ")
let myStringWithImage = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
myStringWithImage.append(myString)
myTextField.attributedText = myStringWithImage
myLabel.attributedText = myStringWithImage

这个苹果thread中没有答案。按照我的想法,我们可以在文本字段中输入表情符号,但不能在文本附件中输入表情符号。在文本字段中,我们为用户提供了输入文本的灵活性。

您可以使用leftView中的UITextField来显示图像。

答案 1 :(得分:0)

您是正确的,NSTextAttachment中没有出现UITextField,我不确定是错误还是UITextField的错误,我将在此处提出雷达并更新响应:

同时,如果您可以将UI元素更改为UILabelUITextView,请访问以下工作文件:

let attachment = NSTextAttachment()
attachment.image = myImage
attachment.bounds = CGRect(origin: .zero, size: myImage.size)

let attributedStr = NSMutableAttributedString(string: self.text ?? "")
attributedStr.insert(NSAttributedString(attachment: attachment), at: 0)

enter image description here