Self Sizing Cells and Dynamic Type

Episode #185 | 18 minutes | published on September 4, 2015
In this episode we'll learn how to implement self-sizing table view cells in iOS 8. We'll also see what the oft-ignored Compression Resistance Priority and Content Hugging Priority are used for, and finally how to implement dynamic type in our application to support dynamic text sizes.

Episode Links

Set up UITableView for Auto-sizing rows

  override func viewDidLoad() {
        super.viewDidLoad()

        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 100

        // ...
    }

Now the cells will initially be laid out using the estimated row height, then autolayout constraints on the visible cells will be calculated to provide actual heights for each cell.

Set up Auto-layout Constraints

You need to make sure that your cell's content are constrained on all sides. Rather that using the content view as an anchor for your content, your content drives the size of the content view.

Take note of the Compression Resistance Priority and Content Hugging Priority when aligning controls of varying size next to each other. The cells want to be their intrinsic size, but when this collides with other constraints, the system needs to know which view can ben squished, and which view can grow larger.

Setting up Dynamic Type

Here we did this in our cell, because that was the owner of our labels.

func awakeFromNib() {
  super.awakeFromNib()
  let nc = NSNotificationCenter.defaultCenter()
  nc.addObserverForName(UIContentSizeCategoryDidChangeNotification, 
     object: nil, 
     queue: NSOperationQueue.mainQueue()) { _ in
       self.prepareForDynamicType()
  }
  prepareForDynamicType()
}

func prepareForDynamicType() {
  titleLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
  numberOfItemsLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1)
}

Now we can respond to changes in font-size by the user and update our font, which will invalidate the layout. This plays nicely with self sizing cells, so they adjust accordingly.

blog comments powered by Disqus