영화 선호도 점수의 텍스트 크기 및 색상 개별 적용하기 위해서는 "NSMutableAttributedString"를 사용하면 됩니다.
private let scoreLabel: UILabel = {
let label = UILabel()
label.textAlignment = .center
label.font = .systemFont(ofSize: 14, weight: .bold) // 기본 폰트 크기
label.backgroundColor = .clear
label.layer.cornerRadius = 20
label.clipsToBounds = true
// ✅ "55%"에서 "%"만 크기 줄이고, "55"는 초록색으로 변경
let fullText = "55%"
let attributedString = NSMutableAttributedString(string: fullText)
// "55" 부분 (0~1 인덱스) 색상 변경 (초록색)
attributedString.addAttribute(.foregroundColor, value: UIColor.green, range: NSRange(location: 0, length: 2))
// "%" 부분 (2번째 인덱스) 색상 유지 (검은색)
attributedString.addAttribute(.foregroundColor, value: UIColor.black, range: NSRange(location: 2, length: 1))
// "%"만 작은 크기로 변경
let smallerFont = UIFont.systemFont(ofSize: 10, weight: .bold) // % 크기 줄이기
attributedString.addAttribute(.font, value: smallerFont, range: NSRange(location: 2, length: 1))
label.attributedText = attributedString
return label
}()
📌 적용 결과
✅ "55"는 초록색
✅ "%"는 검은색 + 글자 크기 작게
📌 점수(Score)에 따라 색상을 동적으로 변경하는 방법
- API에서 데이터를 받아올 때 scoreLabel의 색상을 변경하는 방법
- 데이터를 받은 후 점수를 기반으로 색상을 동적으로 적용
- UI 업데이트가 가능하며, 점수가 바뀔 경우에도 대응 가능.
class ScoreLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
setupLabel()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupLabel() {
textAlignment = .center
font = .systemFont(ofSize: 14, weight: .bold) // 기본 폰트 크기
backgroundColor = .clear
layer.cornerRadius = 20
clipsToBounds = true
}
/// ✅ 점수에 따라 색상 변경하는 메서드
func configure(with score: Int) {
let fullText = "\(score)%"
let attributedString = NSMutableAttributedString(string: fullText)
// 점수에 따라 색상 설정
let scoreColor: UIColor
switch score {
case 80...100:
scoreColor = .green
case 60..<80:
scoreColor = .orange
case 40..<60:
scoreColor = .yellow
default:
scoreColor = .red
}
// "숫자(점수)" 부분 색상 변경
attributedString.addAttribute(.foregroundColor, value: scoreColor, range: NSRange(location: 0, length: fullText.count - 1))
// "%" 부분 (작은 크기 유지)
let smallerFont = UIFont.systemFont(ofSize: 10, weight: .bold)
attributedString.addAttribute(.font, value: smallerFont, range: NSRange(location: fullText.count - 1, length: 1))
attributedString.addAttribute(.foregroundColor, value: UIColor.white, range: NSRange(location: fullText.count - 1, length: 1))
self.attributedText = attributedString
}
}
📌 사용 방법
let scoreLabel = ScoreLabel()
scoreLabel.configure(with: 55) // 점수가 55면 노란색 적용