반응형
문제 상황
- UILabel에서 "근무지 *"와 같이 특정 문자를 강조하려 했으나 에 적용한 색상이 반영되지 않음
- NSMutableAttributedString을 사용했음에도 불구하고 문자가 회색(gray900)으로 표시되어 의도한 빨간색(accent)이 보이지 않는 문제 발생
원인 분석
- NSMutableAttributedString은 속성을 덮어쓰기 방식으로 적용됨
- 전체 문자열에 .foregroundColor = gray900를 마지막에 적용하면서,
- 앞서 설정한 *에 대한 빨간색 설정이 덮어써져 무효화됨
해결방안
- 기본 스타일(전체 폰트 및 색상)은 먼저 설정하고
- 특정 부분 강조()는 가장 마지막에 스타일을 적용하도록 순서 조정
private let workplaceTitle = UILabel().then {
let fullText = "근무지 *"
let attributed = NSMutableAttributedString(string: fullText)
// 전체 스타일 먼저
attributed.addAttribute(.font, value: UIFont.headBold(18), range: NSRange(location: 0, length: fullText.count))
attributed.addAttribute(.foregroundColor, value: UIColor.gray900, range: NSRange(location: 0, length: fullText.count))
// '*'만 마지막에 다시 색상 덮어쓰기
if let starRange = fullText.range(of: "*") {
let nsRange = NSRange(starRange, in: fullText)
attributed.addAttribute(.foregroundColor, value: UIColor.accent, range: nsRange)
}
$0.attributedText = attributed
}반응형