[iOS/Swift] UIFontPickerViewController 를 사용해 폰트 바꾸기
이번 포스팅에서는 UIFontPickerViewController 를 사용해 Label 의 Font 를 바꾸는 방법을 소개하겠습니다.
* UIFontPickerViewController 는 iOS 13버전 이상부터 사용 가능합니다!
공식 문서 : developer.apple.com/documentation/uikit/uifontpickerviewcontroller
Apple Developer Documentation
developer.apple.com
공식 문서에 설명이 충분히 나와있지만 하나씩 살펴보도록 합시다~
별도의 라이브러리 설치 없이 UIKit 에서 제공합니다.
아주 간단하게 버튼 클릭 메소드 안에 아래와 같은 코드 두 줄만 입력해도 바로 폰트 선택 화면이 나옵니다.
@IBAction func tapButton(_ sender: UIButton) {
let fontPicker = UIFontPickerViewController()
present(fontPicker, animated: true, completion: nil)
}
이 때 UIFontPickerViewController.Configuration 을 사용해 여러가지 옵션을 줄 수 있습니다.
만일 configuration 에 includeFaces = true 를 지정하면 폰트 내에 bold, italic 체 옵션을 추가할 수 있습니다.
@IBAction func tapButton(_ sender: UIButton) {
let configuration = UIFontPickerViewController.Configuration()
configuration.includeFaces = true // 옵션 추가
let fontPicker = UIFontPickerViewController(configuration: configuration)
present(fontPicker, animated: true, completion: nil)
}
이 외에도 customize 할 수 있는 여러가지 옵션이 있습니다.
- displayUsingSytstemFont : 글꼴 선택기의 모든 글꼴 이름에 시스템 글꼴을 사용할지 여부를 결정하는 Bool 값. (..?? 이건 공식문서 읽어봐도 잘 이해가지 않는다. )
- filteredTraits : 사용할 글꼴의 유형을 제한할 수 있습니다.
- filteredLanguagePredicate : 언어를 기준으로 글꼴의 유형을 제한할 수 있습니다.
이제 Delegate 을 사용해 label 의 font 를 바꿔봅시다.
fontPicker.delegate = self
extension ViewController: UIFontPickerViewControllerDelegate {
func fontPickerViewControllerDidPickFont(_ viewController: UIFontPickerViewController) {
}
func fontPickerViewControllerDidCancel(_ viewController: UIFontPickerViewController) {
}
}
폰트를 클릭하면 fontPickerVieewControllerDidPickFont 가 호출되고,
취소를 누르면 fontPickerViewControllerDidCancel 메소드가 호출됩니다.
guard let descriptor = viewController.selectedFontDescriptor else { return }
let font = UIFont(descriptor: descriptor, size: 17)
self.mylabel.font = font
DidPickFont 안에 위와 같이 원하는 라벨에 셀렉한 폰트를 지정하면
이렇게 동작합니다~~
간단해서 매우 좋다 ㅎㅎ