현재 진행중인 프로젝트에서 특정 텍스트만 Bold 처리해야하는 상황이 생겨 아래 방법으로 적용하였다.
먼저 텍스트의 특정 부분만 Bold 처리하기위해 NSMutableAttributedString를 사용하여 처리하였고, 처리하는 방법으로는
적용할 테스트 텍스트
let testText = "이름 : 김철수"
1. 적용하고 싶은 폰트 사이즈 / 폰트를 설정
let fontSize = UIFont.boldSystemFont(ofSize: 17)
2. 수정할 텍스트를 NSMutableAttributedString으로 만듬
let attributedStr = NSMutableAttributedString(string: testText)
3. addAttribute를 통해 Attribute를 적용
attributedStr.addAttribute(.font, value: fontSize, range: (testText as NSString).range(of: "이름 : "))
4. 최종적으로 bold 처리된 텍스트를 lable에 적용
subTitle2Lable.attributedText = attributedStr
이렇게 적용하게되면 이름 : 만 Blod 적용된 것을 볼 수 있다.

여러 레이블에 재사용해야하기 때문에 익스텐션으로 확장시켜 재사용하도록 수정!
// Bold 처리가 필요한 Text를 case로 추가
enum BoldStringType: String {
case name = "이름 : "
}
extension String {
func convertBoldString(boldString: BoldStringType) -> NSAttributedString {
let fontSize = UIFont.boldSystemFont(ofSize: 17)
let attributedStr = NSMutableAttributedString(string: self)
attributedStr.addAttribute(.font, value: fontSize, range: (self as NSString).range(of: boldString.rawValue))
return attributedStr
}
}
// 사용하는 곳
let testText = "이름 : 김철수"
subTitle2Lable.attributedText = testText.convertBoldString(boldString: .name)
폰트 이외에도 텍스트 색상, 밑줄, 배경색 등등 NSMutableAttributedString으로 변경할 수 있다.
'iOS' 카테고리의 다른 글
| iOS - StackView에서 Subview 제거할때 주의점 (0) | 2023.07.24 |
|---|---|
| iOS - 커스텀뷰를 테이블뷰와 비슷하게 사용하기 (0) | 2023.07.11 |
| NavigationController 사용시 status Bar Style 바꾸기 (0) | 2022.12.15 |
| navigationBar + scrollView를 함께 사용할때 top 여백 없애는 방법 (2) | 2022.12.01 |
| UICollectionViewCompositionalLayout에서 Cell 동적 높이 적용하기 (0) | 2022.11.01 |