공주가 Label에 색깔 두개 이상 넣는 방법 알려준다

두두·2022년 7월 21일
0

Swift

목록 보기
6/6

안녕 나 또 돌아온 아요공주 두두
오늘은 텍스트 안나누고 색상 여러개 지정하는 법 알려준다.

이렇게 만들거다

label을 두개 만들거나 텍스트를 나눠서 합치는 방법이 있겠지만 공주는 귀찮아서 코드로 해결한다.

일단 UIlabel을 하나 만들어조

@IBOutlet weak var headerTitleLabel: UILabel!

그다음은 label을 잘 꾸며조

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
    headerTitleLabel.text = "우선, 준비해볼까요?"
    headerTitleLabel.font = Pretendard.size18.bold()
}

어랏 그럼 색상은 어케 지정하지? 이제부터 시쟈기야. (사실 끝이야)

// NSMutableAttributedString Type으로 바꾼 text를 저장
let attributedStr = NSMutableAttributedString(string: headerTitleLabel.text!)

// text의 range 중에서 "우선,"이라는 글자를 UIColor를 black으로 변경
attributedStr.addAttribute(.foregroundColor, value: Color.black.getColor(), range: (headerTitleLabel.text! as NSString).range(of: "우선,"))
// text의 range 중에서 "준비해볼까요?"라는 글자를 UIColor를 navy01로 변경
attributedStr.addAttribute(.foregroundColor, value: Color.navy01.getColor(), range: (headerTitleLabel.text! as NSString).range(of: "준비해볼까요?"))

// 설정이 적용된 text를 label의 attributedText에 저장
headerTitleLabel.attributedText = attributedStr

더 효율이 떨어지는 것 같다구?

Assertive

그럼 20000

여기 머 많다 시간날 때 한번 보시길!

https://developer.apple.com/documentation/foundation/nsattributedstring/key

profile
일단 갈기고보는 주니어개발자 두두입니다 :)

0개의 댓글