포스트

Add image to string in UILabel using NSTextAttachment

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.

1
2
3
4
5
6
7
8
9
10
11
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.

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.