개발/Swift
Label Attribute 이미지 처리, 줄넘김 하기
덤벨로퍼
2024. 9. 12. 13:53
요구사항
이미지 + 텍스트 + 이미지 + 텍스트 + 강조텍스트 + 텍스트 형태의 레이아웃 구현이 필요
영역을 넘어갈경우 다음줄로 넘어가면 되는데 그런경우 강조텍스트 + 텍스트 이부분이 같이 다음줄로 넘어가야함
- 1줄
2. 2줄일 경우
해결 방법
이미지와 텍스트를 따로 구현하기에는 줄넘김을 구현하기에 레이아웃 잡기 쉽지 않아보임, 관리할 컴포넌트가 너무많아 비효율적이라 판단 하여 Attribute Text 로 구현
- 텍스트에 이미지 추가하기
private func getImageAttributedString(image: UIImage) -> NSAttributedString {
let imageAttachment = NSTextAttachment(image: image)
imageAttachment.bounds = .init(x: 0, y: -1, width: 12, height: 12)
let imageAttributedString = NSAttributedString(attachment: imageAttachment)
return imageAttributedString
}
NSTextAttachment에 이미지를 쉽게 추가할수 있다.
여기에 사이즈를 꼭 지정해줘야했다 Label의 font 사이즈만큼 자동으로 나오지 않음
NSAttributedString 에 attatchment를 넣어서 Label에 추가할수 있음
let popularityText = NSMutableAttributedString()
popularityText.append(getImageAttributedString(image: likeImage)) //이미지 추가
popularityText.append(NSAttributedString(string: " \\(likeCount) · ")) //텍스트 추가
popularityLabel.attributedText = popularityText
2. 특정 영역부터 줄넘김 시키기
“주문수” 부터 줄넘김을 하기위해 일단 attribute에 line break mode 세팅
NSAttributedString 생성할때 이 속성 넣어줄거임
private func getLineHeightAttributes() -> [NSAttributedString.Key: Any] {
let style = NSMutableParagraphStyle()
style.maximumLineHeight = 16
style.minimumLineHeight = 16 //line height 세팅
style.lineBreakMode = .byWordWrapping //띄어쓰기 기준 줄넘김
let attributes: [NSAttributedString.Key: Any] = [
.paragraphStyle: style,
]
return attributes
}
// NSAttributedString 에 세팅할것
그리고 주문수부터 이어지는 Text 를 묶어서 NSAttributedString 구성
//색상 속성
var textColorAttribute: [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.grey800]
//색생 속성 추가한 Attr String
var textColorAttribute: [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.grey800]
textColorAttribute.merge(getLineHeightAttributes()) // 색상 속성 + 줄높이 속성 추가
let orderCountAttributedString = NSAttributedString(string: "주문수 ", attributes: textColorAttribute)
popularityText.append(NSAttributedString(string: orderCount, attributes: getLineHeightAttributes()))