[iOS] NSTextAttachment

모리스·2023년 10월 6일
0

iOS

목록 보기
7/14
post-thumbnail

iOS 앱을 개발하던 중 텍스트 사이에 이미지를 붙여야하는 상황이 생긴다. Label사이에 ImageView를 끼워 넣는것도 여간 귀찮은 작업이고 그게 맞는 방법인건 아닌거 같아 이번 노트에서는 NSAttributedString의 text에 이미지를 넣는 방법을 작성하려한다.


방법은 간단하다. NSMutableAttributedString 인스턴스에 NSTextAttachment를 사용하여 UILabel에 image를 삽입할 수 있다.

let label: UILabel = UILabel()
let mutableAttributedString = NSMutableAttributedString(string: "테스트")
let attachmentText = NSTextAttachment()
attachmentText.image = UIImage(named: "testImage")
attachmentText.bounds = CGRect(x: 0.0, y: 0.0, width: 18.0, height: 18.0)
mutableAttributedString.append(NSAttributedString(attachment: attachmentText))

label.attributedText = mutableAttributedString

이렇게 하면 Label text뒤에 18x18 사이즈의 image가 붙는다.

profile
모바일 앱 개발 노트 :)

0개의 댓글