Dynamic Type and View Layout

Aug 8, 2019

👓🌳 image 1*hNcTzdrygIGoIV09 RB9qQ Replicating Apple’s Dynamic Type just like in Apple stock apps. Download Project Apple enables user to change the font size of there app and Apple app set a good example in there app such as Music and Contact. You can play around with the setting by going in Setting > Accessibility > Larger Text then flip the switch and drag the bar to maximum. When you go back to Apple Music app, the layout will change. image before and after We begin by creating a new project. In storyboard we put a nested stackView. Outside stackView contains imageView and a stackView with all the lables. Put constraints accordingly. image We also constraint imageView with aspect ratio and width. image Connect outside stackView to its viewController. image Then we add the following code

////  ViewController.swift
//import UIKitclass ViewController: UIViewController {    
    @IBOutlet weak var stackView: UIStackView!    
    override func viewDidLoad() {        
    super.viewDidLoad()        
    // Do any additional setup after loading the view.    
  }    
  //1    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)                //2        
    if previousTraitCollection?.preferredContentSizeCategory != traitCollection.preferredContentSizeCategory {            
      let contentSize = traitCollection.preferredContentSizeCategory
      if contentSize.isAccessibilityCategory {                
        stackView.axis = .vertical                
        stackView.alignment = .leading                
        stackView.spacing = 2            
      } else {
        stackView.axis = .horizontal                
        stackView.alignment = .center                
        stackView.spacing = 6            
      }      
    }    
  }
}

We add a

override func traitCollectionDidChange(_previousTraitCollection:UITraitCollection?)

To detect when font size changes. We check whether user is using accessibility font scale and change our stackView accordingly. You can use Xcode’s Accessibility Inspector to control Font size on your simulator. image 1*8rBD5SsNKhkdT-Bs u5e7A This post is inspired by UseYourLoaf’s blog

Confusians

© 2015 - 2021