UIButton에 font 설정 오류 해결하기
NSAttributedString.Key.font를 이용해 UIButton 글꼴 크기, 종류 설정하기
요약: UIButton의 setAttributedTitle 함수를 이용해 해결한다.
여는 글
UIButton 내 titleLabel에 스타일 적용이 안되는 문제가 있었다. 이 글은 해당 문제를 해결하는 확실한 방법을 소개한다.
스타일 적용을 위해 button.titleLabel?.font
를 통해 설정하는 것은 어느 것도적용이 안되었다. 코드는 다음과 같이 작성했다.
button.setTitle("모음집 추가하기", for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 20, weight: .black)
이 코드를 동작하면 아래 사진과 같이 보인다.
deprecated된 사항도 아니고 당연히 될 줄 알았는데 UIFont.systemFont(ofSize: 20, weight: .black)
의 두 가지 설정 모두 적용되지 않았다. 혹시 몰라 각각 따로 적용해보아도 마찬가지였고, system font가 아닌 새로운 글꼴을 설정해도 마찬가지로 적용되지 않았다.
그래서 방법을 찾아보았고 이 방법 외에 지금까지는 다른 방법은 다 실패했었다.
해결 방법
순서를 먼저 알아보자.
UIButton 선언
[NSAttributedString.Key : Any] 배열 생성
setAttributedTitle 함수로 설정이 적용된 NSAttributedString 할당
1. UIButton 선언
UIButton을 선언한다. 이 때 주의할 것이 있다. setAttributedTitle
를 사용할 것이기에 setTtitle
은 사용할 필요가 없다.
let button: UIButton = UIButton()
2. [NSAttributedString.Key : Any] 배열 만들기
NSAttributedString.Key에 있는 미리 선언된 요소를 사용하여 설정한다. 글꼴을 설정할 것이기 때문에 NSAttributedString.Key.font를 사용하고, value 값으로는 UIFont가 할당된다. (배열은 [NSAttributedString.Key : Any]이기 때문에 배열에 글꼴 외에 다른 설정이 필요하다면 추가하도록 한다.)
let attributes = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 20, weight: .black)]
3. setAttributedTitle 함수로 설정이 적용된 NSAttributedString 할당
setAttributedTitle
은 NSAttributedString값을 매개 변수로 받는다. NSAttributedString은 string
값인 string과 [NSAttributedString.Key : Any\]
값을 가지는 attributes 항목을 필요로한다. 즉, 버튼에 입력하고 싶은 글(string)과 설정하고 싶은 설정 내용(attributes)을 담은 객체가 NSAttributedString이고, 이걸 버튼에 적용하는 함수가 setAttributedTitle
인 것이다.
button.setAttributedTitle(NSAttributedString(string: "모음집 추가하기", attributes: attributes), for: .normal)
적용한 결과는 아래 사진과 같다.
결과
의도한대로 적용되었다.
전체 코드
let button: UIButton = UIButton()
let attributes = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 20, weight: .black)]
button.setAttributedTitle(NSAttributedString(string: "모음집 추가하기", attributes: attributes), for: .normal)
여담
실제 사용하려는 디자인과는 다르지만, 확실히 적용되는지 확인하기 위해 일부러 black에 20으로 시도해봤다. 버튼 외의 요소에도 비슷한 형태의 오류가 발견될 경우 이 방법을 사용해볼 예정이다.