Skip to content

Add image to string in UILabel using NSTextAttachment

1 min read

Sometimes you need to add image to a string in a UILabel, but using UIImageView gets complicated and sometimes not efficient. But Apple provides a simpler way, using NSAttributedString and NSTextAttachment. Here’s how you do it.

let stringWithImage = NSMutableAttributedString(string: "Completed")

let imageAttachment = NSTextAttachment()
imageAttachment.image = UIImage(named: "completeIcon")

let completeImageString = NSAttributedString(attachment: imageAttachment)

stringWithImage.append(NSAttributedString(string: " "))
stringWithImage.append(completeImageString)

labelComplete.attributedText = stringWithImage

This way is more easier than using UIImageView. We don’t need any Auto Layout, just a plain NSMutableAttributedString.


Share this post on:

Previous Post
git 강의 때 들었던 내용 정리
Next Post
개인적으로 추천하는 도움이 되는 iOS 공부 자료