Skip to content

Instantly share code, notes, and snippets.

@douglashill
Created April 13, 2019 01:15
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save douglashill/867b3ba920f18278fdbcc9a7c6a498be to your computer and use it in GitHub Desktop.
Save douglashill/867b3ba920f18278fdbcc9a7c6a498be to your computer and use it in GitHub Desktop.
Experimenting altering an iOS app size class to be responsive to the Dynamic Text size.
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