라벨과 이미지를 같이 사용하여 구현해야 할 뷰가 있었고 그 부분을 포스팅 하려 한다.
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 하면 끝!
'IOS' 카테고리의 다른 글
[IOS] UserInterfaceStyle (0) | 2020.12.22 |
---|---|
[IOS] 이미지와 라벨을 같이 사용한 NavigationBarButtonItem (0) | 2020.12.21 |
[IOS] User Event & MainRunLoop (0) | 2020.12.19 |
[IOS] PickerView의 element를 직접구성하는 방법 (0) | 2020.12.15 |
[IOS] Label의 text에따라 유동적인 ScrollView 만들기 (0) | 2020.12.12 |