하나의 UILabel의 텍스트로 "팔로워 326" 와 같이 일부 폰트 변경하기
- "팔로워 326" 표현하기
- 하나의 UILabel 안에서 “팔로워”는 weight : 400, “326”은 600의 weight을 가지고 있음
해결 방안 : NSMutableAttributedString 사용
NSMutableAttributedString | Apple Developer Documentation
A mutable string with associated attributes (such as visual style, hyperlinks, or accessibility data) for portions of its text.
developer.apple.com
- NSMutableAttributedString : 문자열의 속성을 변경할 수 있는 문자열 타입
- 문자열의 타입을 NSMutableAttributedString 으로 변경한 후 addAttribute(_:value:range:) 메서드를 사용하여 문자열의 특정 범위의 속성 변경
- NSMutableAttributedString.addAttribute()
- name
- 속성 이름을 지정하는 문자열
- ex) font, foregroundColor, backgroundColor, strokeColor 등
- value
- name과 연관된 속성 값
- 첫 번째 파라미터에서 선택한 속성 중 변경하고 싶은 값
- ex) font - font의 사이즈, 굵기, 폰트 스타일 등을 지정하는 것
- range
- value 값으로 변경할 문자 범위
- 원하는 속성으로 변경할 문자열의 특정 범위 지정
- name
private lazy var lblFollower : UILabel = {
let label = UILabel()
var follower = "326"
var text = "팔로워 \\(follower)"
label.font = .systemFont(ofSize: 12) // attributed 적용 전 작성! (적용 후 작성하면 이 폰트로 덮여짐)
let attributedText = NSMutableAttributedString(string: text)
attributedText.addAttribute(.font, value: UIFont.systemFont(ofSize: 12, weight: .semibold), range: (text as NSString).range(of: follower))
label.attributedText = attributedText
return label
}()
- https://developer.apple.com/documentation/foundation/nsmutableattributedstring
- https://developer.apple.com/documentation/foundation/nsmutableattributedstring/1417080-addattribute
- https://limjs-dev.tistory.com/102
NSMutableAttributedString | Apple Developer Documentation
A mutable string with associated attributes (such as visual style, hyperlinks, or accessibility data) for portions of its text.
developer.apple.com
addAttribute(_:value:range:) | Apple Developer Documentation
Adds an attribute with the given name and value to the characters in the specified range.
developer.apple.com
Swift) 문자열의 특정 범위의 속성을 변경해보자 NSMutableAttributedString
NSMutableAttributedString 하나의 레이블에서 특정 부분만 폰트나 사이즈를 변경해주고싶었는데.. 범위를 지정해서 특정 범위에 있는 문자열을 빼오고 원래의 문자열의 특정범위를 빈값으로 변경해버
limjs-dev.tistory.com
'Swift' 카테고리의 다른 글
Swift - 내비게이션 화면 전환 시 애니메이션 지연 문제 (5) | 2024.10.09 |
---|---|
Swift - TabBarItem 이미지 렌더링 이슈 (5) | 2024.10.09 |
Swift - UIButton - Image, Title 위치 설정 (2) | 2024.09.30 |
Swift - 구조체 정의 (Decodable) - Codingkey 사용 (1) | 2024.08.10 |
Swift - Xcode 프로젝트 생성 (1) | 2024.06.24 |