Forked from douglashill/AdaptiveTraitsContainer.swift
Created
April 14, 2019 22:15
-
-
Save alemar11/809a112fa906ead856760db9f2d568c9 to your computer and use it in GitHub Desktop.
Experimenting altering an iOS app size class to be responsive to the Dynamic Text size.
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
import UIKit | |
/// A wrapper view controller that makes the horizontal size class | |
/// be based on both the Dynamic Text size and the width available. | |
class AdaptiveTraitsContainer: UIViewController { | |
let wrappedViewController: UIViewController | |
init(wrappedViewController: UIViewController) { | |
self.wrappedViewController = wrappedViewController | |
super.init(nibName: nil, bundle: nil) | |
} | |
required init?(coder aDecoder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
addChild(wrappedViewController) | |
view.addSubview(wrappedViewController.view) | |
NSLayoutConstraint.activate([ | |
wrappedViewController.view.topAnchor.constraint(equalTo: view.topAnchor), | |
wrappedViewController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), | |
view.trailingAnchor.constraint(equalTo: wrappedViewController.view.trailingAnchor), | |
view.bottomAnchor.constraint(equalTo: wrappedViewController.view.bottomAnchor), | |
]) | |
wrappedViewController.didMove(toParent: self) | |
} | |
override func viewWillAppear(_ animated: Bool) { | |
super.viewWillAppear(animated) | |
NotificationCenter.default.addObserver(self, selector: #selector(updateTraitCollection_), name: UIContentSizeCategory.didChangeNotification, object: nil) | |
} | |
override func viewDidDisappear(_ animated: Bool) { | |
NotificationCenter.default.removeObserver(self, name: UIContentSizeCategory.didChangeNotification, object: nil) | |
super.viewDidDisappear(animated) | |
} | |
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { | |
super.viewWillTransition(to: size, with: coordinator) | |
updateTraitCollection(withSize: size) | |
} | |
@objc private func updateTraitCollection_() { | |
updateTraitCollection(withSize: view.bounds.size) | |
} | |
private func updateTraitCollection(withSize size: CGSize) { | |
let widthThreshold = 30 * UIFontDescriptor.preferredFontDescriptor(withTextStyle: .body).pointSize | |
let sizeClass: UIUserInterfaceSizeClass = size.width < widthThreshold ? .compact : .regular | |
setOverrideTraitCollection(UITraitCollection(horizontalSizeClass: sizeClass), forChild: wrappedViewController) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment