Swift 3 version
let attachment = NSTextAttachment()
attachment.image = UIImage(named: "plus")
attachment.bounds = CGRect(x: 0, y: 0, width: 10, height: 10)
let attachmentStr = NSAttributedString(attachment: attachment)
let myString = NSMutableAttributedString(string: "")
myString.append(attachmentStr)
let myString1 = NSMutableAttributedString(string: "My label text")
myString.append(myString1)
lbl.attributedText = myString
UILabel Extension
extension UILabel {
func set(text:String, leftIcon: UIImage? = nil, rightIcon: UIImage? = nil) {
let leftAttachment = NSTextAttachment()
leftAttachment.image = leftIcon
leftAttachment.bounds = CGRect(x: 0, y: -2.5, width: 20, height: 20)
if let leftIcon = leftIcon {
leftAttachment.bounds = CGRect(x: 0, y: -2.5, width: leftIcon.size.width, height: leftIcon.size.height)
}
let leftAttachmentStr = NSAttributedString(attachment: leftAttachment)
let myString = NSMutableAttributedString(string: "")
let rightAttachment = NSTextAttachment()
rightAttachment.image = rightIcon
rightAttachment.bounds = CGRect(x: 0, y: -5, width: 20, height: 20)
let rightAttachmentStr = NSAttributedString(attachment: rightAttachment)
if semanticContentAttribute == .forceRightToLeft {
if rightIcon != nil {
myString.append(rightAttachmentStr)
myString.append(NSAttributedString(string: " "))
}
myString.append(NSAttributedString(string: text))
if leftIcon != nil {
myString.append(NSAttributedString(string: " "))
myString.append(leftAttachmentStr)
}
} else {
if leftIcon != nil {
myString.append(leftAttachmentStr)
myString.append(NSAttributedString(string: " "))
}
myString.append(NSAttributedString(string: text))
if rightIcon != nil {
myString.append(NSAttributedString(string: " "))
myString.append(rightAttachmentStr)
}
}
attributedText = myString
}
}