본문 바로가기

IOS

[IOS] AttributedString을 사용한 Label에 Image 속성 추가

라벨과 이미지를 같이 사용하여 구현해야 할 뷰가 있었고 그 부분을 포스팅 하려 한다.

 

Attribute를 이용하여 진행 할껀데 

물론 라벨 따로 이미지뷰 따로 레이아웃을 잡아 진행 할 수 있기도 하다.

이부분은 각자의 선택에 맡기겠다.

 

시작은 아주 간단하게 라벨을 하나 만들겠다.

 

let label: UILabel = {
	let label = UILabel()
	label.text = "testtest"
	return label
}()

 

이 라벨의 레이아웃을 잡아 준다면

 

 

이렇게 보일텐데 지금 해보려 하는건 attributedText를 활용한 구현이니깐

 

let attributedString = NSMutableAttributedString(string: "첫번째 문장")

 

NSMutableAttributedString의 인스턴스를 만들꺼다.

 

이놈은 간략히 보자면

 

텍스트 콘텐츠의 다양한 부분과 관련된 속성 (예 : 비주얼 스타일, 하이퍼 링크 또는 접근성 데이터)도 포함하는 변경 가능한 문자열 개체입니다

 

라고한다.

지금 하려하는게 비주얼 스타일에 속하는거같다.

 

let label: UILabel = {
        let label = UILabel()
        
        let attributedString1 = NSMutableAttributedString(string: "첫번째 문장")
        
        let imageAttachment1 = NSTextAttachment()
        imageAttachment1.image = UIImage(named: "testimage")
        imageAttachment1.bounds = CGRect(x: 0, y: 0, width: 15, height: 15)
        
        attributedString1.append(NSAttributedString(attachment: imageAttachment1))
        
        label.attributedText = attributedString1
        return label
    }()

 

그리고 나서 NSTextAttachment를 생성 할껀데 이놈은

 

속성이있는 문자열 및 관련 개체의 첨부 속성 값입니다.

문자열에 뭔가 속성을 추가 해준다는 느낌인데 이놈을 타고 들어가면 

 

image라는 변수가 있는걸 확인 할 수 있다.

이 image 변수에 우리는 image를 넣어주꺼다.

그담 bounds로 접근해서 CGRect를 설정 해주고

처음에 만들었던 NSMutableAttributedString 인스턴스에다가 

 

방금 이미지를 넣고 사이즈를 설정 해놓은 NSTextAttachment를 append 한다.

마지막으로 NSMutableAttributedString을 label의 attributedText에 할당을 해주면

 

 

이런식으로 라벨옆에 이미지가 붙어있는걸 확인할 수 있다.

 

그리고 텍스트를 "첫번째 문장" 이라고 쓴 이유가 있다.

위에서 NSTextAttachment를 append 한다고 했는데 계속 연결할 수 있을거라고 예상한 사람 있을꺼다.

그럼 붙혀보겠다.

 

코드를 보자면 반복이다.

let label: UILabel = {
        let label = UILabel()
        
        let attributedString1 = NSMutableAttributedString(string: "첫번째 문장")
        let imageAttachment1 = NSTextAttachment()
        imageAttachment1.image = UIImage(named: "testimage")
        imageAttachment1.bounds = CGRect(x: 0, y: 0, width: 15, height: 15)
        attributedString1.append(NSAttributedString(attachment: imageAttachment1))
        
        
        let attributedString2 = NSMutableAttributedString(string: "두번째문장")
        let imageAttachment2 = NSTextAttachment()
        imageAttachment2.image = UIImage(named: "testimage")
        imageAttachment2.bounds = CGRect(x: 0, y: 0, width: 15, height: 15)
        attributedString2.append(NSAttributedString(attachment: imageAttachment2))
        
        attributedString1.append(attributedString2)
        
        label.attributedText = attributedString1
        return label
    }()

 

아까 했던거처럼 NSMutableAttributedString를  만들고 NSTextAttachment를 만들고 이미지 넣고 사이즈 설정하고 

새로만든 NSMutableAttributedString을 기존에 있던 NSMutableAttributedString에 append 하면 끝!