我试图将图像添加为NSTextAttachment
到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
最佳答案
UITextField
不允许NSTextAttachment
,但UILabel
允许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
这个苹果没有答案。根据我的想法,我们可以在文本字段中输入emojis,但不能在文本附件中输入emojis。在文本字段中,我们为用户输入文本提供了灵活性。
您可以使用
leftView
的UITextField
来显示图像。