Skip to content

Instantly share code, notes, and snippets.

@krummler
Created April 15, 2020 11:25
Show Gist options
  • Save krummler/de3d8bb87f6a6712062a7ec9d2802b46 to your computer and use it in GitHub Desktop.
Save krummler/de3d8bb87f6a6712062a7ec9d2802b46 to your computer and use it in GitHub Desktop.
class WeightAdheringLabel: UILabel {
private var originalFont: UIFont?
override var font: UIFont! {
set {
self.originalFont = newValue
if traitCollection.legibilityWeight == .bold {
super.font = newValue.fontDescriptor.withSymbolicTraits(.traitBold).map { UIFont(descriptor: $0, size: newValue.pointSize) } ?? newValue
} else {
super.font = newValue
}
}
get {
return super.font
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
if traitCollection.legibilityWeight == .bold && previousTraitCollection?.legibilityWeight != .bold {
super.font = originalFont?.fontDescriptor.withSymbolicTraits(.traitBold).map { UIFont(descriptor: $0, size: 0) } ?? font
} else if traitCollection.legibilityWeight == .regular && previousTraitCollection?.legibilityWeight != .regular {
super.font = originalFont ?? font
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment