This does not work on UITextField. It only works on UILabel.
Here is a UILabel extension based on your code (Swift 2.0)
extension UILabel { func addImage(imageName: String) { let attachment:NSTextAttachment = NSTextAttachment() attachment.image = UIImage(named: imageName) let attachmentString:NSAttributedString = NSAttributedString(attachment: attachment) let myString:NSMutableAttributedString = NSMutableAttributedString(string: self.text!) myString.appendAttributedString(attachmentString) self.attributedText = myString } }
EDIT:
here is a new version that allows you to add an icon before or after the tag. There is also a function to remove the icon from the label
extension UILabel { func addImage(imageName: String, afterLabel bolAfterLabel: Bool = false) { let attachment: NSTextAttachment = NSTextAttachment() attachment.image = UIImage(named: imageName) let attachmentString: NSAttributedString = NSAttributedString(attachment: attachment) if (bolAfterLabel) { let strLabelText: NSMutableAttributedString = NSMutableAttributedString(string: self.text!) strLabelText.appendAttributedString(attachmentString) self.attributedText = strLabelText } else { let strLabelText: NSAttributedString = NSAttributedString(string: self.text!) let mutableAttachmentString: NSMutableAttributedString = NSMutableAttributedString(attributedString: attachmentString) mutableAttachmentString.appendAttributedString(strLabelText) self.attributedText = mutableAttachmentString } } func removeImage() { let text = self.text self.attributedText = nil self.text = text } }
source share