[Swift] 하나의 UIButton에서 글자마다 다른 색상을 주는 법

김혜수·2021년 8월 4일
0

저는 지금 애플 기본 날씨앱 클론코딩을 하고 있는데요, 지역을 선택하는 뷰에 가 보면

좌측 하단에 섭씨와 화씨를 바꾸는 버튼을 볼 수 있습니다.
이게 다른 버튼이 아니라 하나의 버튼인 것 같아서 하나의 버튼 안에서 ºC는 흰색으로, ºF 는 회색으로 만드는 방법을 포스팅해보려고 합니다!

필요한 내용은 NSMutableAttributedStringsetAttributedTitle 입니다.

먼저 NSMutableAttributedString을 이용해서 버튼에 들어가는 문자열의 색상을 지정해줍니다.


// temperatureButton 의 titleLable을 NSMutableAttributedString으로 바꿔서 attributedStr 에 저장함
let attributedStr = NSMutableAttributedString(string: (temperatureButton.titleLabel?.text)!)

// text중 ºC에 해당하는 곳에 흰색을 줌
attributedStr.addAttribute(.foregroundColor, value: UIColor.white, range: ((temperatureButton.titleLabel?.text)! as NSString).range(of: "ºC"))

// text중 / ºF에 해당하는 곳에 회색을 줌
attributedStr.addAttribute(.foregroundColor, value: UIColor.gray, range: ((temperatureButton.titleLabel?.text)! as NSString).range(of: "/ ºF"))

이렇게 한 후, setAttributedTitle을 이용해 uibutton에 적용해주면 됩니다.

temperatureButton.setAttributedTitle(attributedStr, for: .normal)
profile
iOS를 좋아하는 사람

0개의 댓글