Skip to content

Instantly share code, notes, and snippets.

@indragiek
Last active August 25, 2017 15:08
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save indragiek/59cc1be44a484e13ff38 to your computer and use it in GitHub Desktop.
Save indragiek/59cc1be44a484e13ff38 to your computer and use it in GitHub Desktop.
UILabel subclass that automatically adjusts the font when the global dynamic type setting changes.
//
// DynamicTypeLabel.swift
//
// Created by Indragie on 10/16/14.
// Copyright (c) 2014 Indragie Karunaratne. All rights reserved.
//
import UIKit
class DynamicTypeLabel : UILabel {
private var textStyle: String?
func commonInit() {
textStyle = textStyleForCurrentFont()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("dynamicTypeSettingChanged"), name: UIContentSizeCategoryDidChangeNotification, object: nil)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
@objc func dynamicTypeSettingChanged() {
if let textStyle = textStyle {
font = UIFont.preferredFontForTextStyle(textStyle)
}
}
func textStyleForCurrentFont() -> String? {
let styles = [
UIFontTextStyleBody,
UIFontTextStyleHeadline,
UIFontTextStyleSubheadline,
UIFontTextStyleFootnote,
UIFontTextStyleCaption1,
UIFontTextStyleCaption2
]
for style in styles {
if font == UIFont.preferredFontForTextStyle(style) {
return style
}
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment