I'm trying to add an image as NSTextAttachment
to UITextField
, but all I get is ,
Code within custom 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
will not allow NSTextAttachment
but UILabel
allows the NSTextAttachment
.
For Example:
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
No answers in this apple thread. As of my thought we can enter emojis in text field but not text attachment. In text field we are giving flexibility to user for entering text.
You can use the leftView
of UITextField
to display image.