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

Cant add image as NSTextAttachment to UITextField

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

自定义代码 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

你是对的,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)

UITextField 不允许 NSTextAttachmentUILabel 允许 NSTextAttachment

例如:

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。根据我的想法,我们可以在文本字段中输入表情符号,但不能在文本附件中输入。在文本字段中,我们为用户提供了输入文本的灵活性。

可以使用UITextFieldleftView来显示图片。