We have to add all the extension of related UIFramework for which we have to use dynamic font size of custom font in iOS-11+ such as UILabel, UIButton, UITextField, UITextView. Code is given in swift 4.2. We just need to use these custom classes instead of native ios classes to see effect of dynamic fonts in app.
Here first is Label:
class AppLabel: UILabel {
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if #available(iOS 11.0, *) {
self.font = UIFontMetrics.default.scaledFont(for: self.font)
self.adjustsFontForContentSizeCategory = true
// Fallback on earlier versions
} else {
// Fallback on earlier versions
}
}
}
Here 2nd is UIButton:
class AppButton: UIButton {
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if #available(iOS 11.0, *) {
self.titleLabel?.font = UIFontMetrics.default.scaledFont(for: self.titleLabel?.font ?? UIFont())
self.titleLabel?.adjustsFontForContentSizeCategory = true
} else {
// Fallback on earlier versions
}
}
}
Here 3rd is UITextField:
class AppTextField: UITextField {
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if #available(iOS 11.0, *) {
self.font = UIFontMetrics.default.scaledFont(for: self.font ?? UIFont())
self.adjustsFontForContentSizeCategory = true
} else {
// Fallback on earlier versions
}
}
}
Last one in UITextView:
class AppTextView: UITextView {
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if #available(iOS 11.0, *) {
self.font = UIFontMetrics.default.scaledFont(for: self.font ?? UIFont())
self.adjustsFontForContentSizeCategory = true
} else {
// Fallback on earlier versions
}
}
}