Last active
August 25, 2017 15:08
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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