skip to content

In UIKit, how should a video call screen rearrange its participant grid on rotation and iPad window resizing, using viewWillTransition(to:with:) and trait-change registration?

level: middleimportance: should knowfreq 58%

answer

  1. a size change is not a trait change
  2. the new size arrives before the bounds change
  3. animate with the coordinator, call super
  4. register for only the traits you use
  5. iOS 17 deprecated traitCollectionDidChange(_:)

basics

~10 s

Override viewWillTransition(to:with:) for the new size, call super, and animate the grid change inside the coordinator's animate(alongsideTransition:completion:). For size-class changes, register in viewDidLoad() with registerForTraitChanges(:handler:) (iOS 17), which replaced traitCollectionDidChange(:).

solid answer

~40 s

Rotation and iPad window resizing change the view controller's size, and UIKit announces that with `viewWillTransition(to:with:)` before the view's bounds change; the `size` argument is the new size. Call `super` so the message reaches child view controllers, then make the grid change inside `coordinator.animate(alongsideTransition:completion:)` so tiles move with the system animation. Whether the grid switches column count is often a trait question: a resize can change the horizontal size class. Since iOS 17, register for exactly that trait with `registerForTraitChanges([UITraitHorizontalSizeClass.self])` in `viewDidLoad()`; the handler receives the view controller and the previous trait collection. `traitCollectionDidChange(_:)` is deprecated from iOS 17, and UIKit removes registrations when the object goes away.

code

swift · 29 lines
swift
import UIKit

final class TileGridViewController: UIViewController {
    private let grid = UICollectionView(
        frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(grid)
        // iOS 17: observe only the trait that changes the grid's shape.
        registerForTraitChanges([UITraitHorizontalSizeClass.self]) { (self: Self, previous: UITraitCollection) in
            self.applyColumns(for: self.traitCollection.horizontalSizeClass)
        }
    }

    override func viewWillTransition(to size: CGSize, with coordinator: any UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        coordinator.animate(alongsideTransition: { _ in
            self.grid.collectionViewLayout.invalidateLayout()
            self.view.layoutIfNeeded()
        }, completion: { _ in
            self.grid.flashScrollIndicators()
        })
    }

    private func applyColumns(for sizeClass: UIUserInterfaceSizeClass) {
        grid.collectionViewLayout.invalidateLayout()
    }
}

go deeper

for a junior

Know that rotation and resizing call viewWillTransition(to:with:), and that size classes are traits that may or may not change with it.

for a middle

Explain the coordinator's alongside animation, why super must be called, and how registerForTraitChanges(:handler:) replaced traitCollectionDidChange(:) in iOS 17.

for a senior

Keep trait handlers cheap, register only the traits a screen uses, and make child view controllers receive forwarded size changes in multitasking layouts.

for a principal

Decide when a screen's layout should key off size classes versus exact sizes, so iPad window sizes do not each need their own code path.

## Two different signals A video call screen that lays its participant tiles out in a grid has to react to two kinds of change, and UIKit reports them separately: - A **size change**: the view controller's view is about to get a new size. Rotation causes one, and so does resizing the app's window on iPad when it shares the screen with another app. - A **trait change**: a value in the view controller's **trait collection** (`UITraitCollection`) changes. The horizontal and vertical **size classes**, `.compact` or `.regular`, are traits; so are appearance, Dynamic Type size and display scale. A size change may or may not change a size class. Rotation always changes the size; whether it changes a size class depends on the device and orientation. Making a narrow iPad window wider can flip the horizontal size class from compact to regular. Code that needs the exact size listens for the size change; code that only cares about the coarse category listens for the trait. ## viewWillTransition(to:with:) `viewWillTransition(to:with:)` belongs to the `UIContentContainer` protocol, which view controllers adopt. UIKit calls it **before** changing the size of the view, so inside it `view.bounds` still holds the old size and the `size` parameter holds the new one. 1. **Call `super`.** View controllers forward the size change to their views and child view controllers; skipping `super` means participant tiles that are child view controllers never hear about it. 2. **Animate with the coordinator.** The `coordinator` is a `UIViewControllerTransitionCoordinator`. Changes made inside `animate(alongsideTransition:completion:)` run in the same animation as the system's resize, so tiles slide to their new places instead of jumping. 3. **Finish in the completion closure**, for work that should wait until the new size is in place, such as recentring on the active speaker. ## Trait-change registration (iOS 17) Before iOS 17, view controllers overrode `traitCollectionDidChange(_:)` and compared the previous collection with the current one. That method is **deprecated from iOS 17** in favour of the `UITraitChangeObservable` protocol, which `UIView`, `UIViewController` and `UIPresentationController` adopt: - `registerForTraitChanges(_:handler:)` takes an array of trait types, such as `[UITraitHorizontalSizeClass.self]`, and a closure that receives the trait environment and the previous trait collection. - Variants take a target and action, or an action on `self`. - Registering in `viewDidLoad()` is enough: **UIKit cleans up registrations at the end of the object's lifetime**, and `unregisterForTraitChanges(_:)` is only for changing what you observe. Apple's documentation adds a performance rule: traits can change more than once before the system updates a view, so a handler should do little work. For the grid, invalidating the collection view's layout or changing a column count property and letting the next layout pass do the rest is right; rebuilding every tile is not. From iOS 18, `viewWillLayoutSubviews()` and `viewDidLayoutSubviews()` also support **automatic trait tracking**: UIKit records the traits they read from the view controller's and the view's trait collections and runs the update again when one of them changes, so a layout computed there from a size class can stay current without a registration. ## Putting the call screen together | Change | Callback | What the grid does | |---|---|---| | Rotation, window resize | `viewWillTransition(to:with:)` | animates tile frames with the coordinator | | Horizontal size class flips | handler from `registerForTraitChanges(_:handler:)` | switches between a strip and a grid | | Ordinary layout pass | `viewDidLayoutSubviews()` | sizes tiles from the current bounds | ## Mistakes to avoid - **Doing size work in a trait handler.** A size-class handler does not run on a rotation that leaves every size class unchanged, so a grid that needs exact tile sizes misses the change. - **Doing class work on every size change.** Rebuilding the arrangement in each `viewWillTransition(to:with:)` call, even when the size class did not change, repeats work the trait registration would do only when needed. - **Registering in `viewWillAppear(_:)`.** It runs on every appearance, so each return adds another registration and the handler runs several times per change. - **Reading `view.bounds` too early.** At the top of `viewWillTransition(to:with:)` it still holds the old size. - **Forgetting `super`.** Child tile view controllers then never receive the size change. Child tiles can be given traits of their own through `traitOverrides` on each child view controller (iOS 17), which replaced `setOverrideTraitCollection(_:forChild:)`. For trait transitions that a container wants to animate, `willTransition(to:with:)` delivers the incoming trait collection with a coordinator before the traits change.

  • In UIKit, inside viewWillTransition(to:with:), why can't the code read view.bounds to lay out the new grid?
    UIKit calls `viewWillTransition(to:with:)` before it changes the view's size, so `view.bounds` still has the old size. Layout for the new size uses the `size` parameter, or is placed inside `animate(alongsideTransition:completion:)`, where the view already has its new bounds and the change animates with the resize.
  • In UIKit, when would a view controller still call unregisterForTraitChanges(_:)?
    Only when it needs to change which traits it observes while it is alive, for example dropping a size-class registration once the screen switches to a fixed layout. Otherwise UIKit removes trait registrations when the view or view controller is deallocated, so registrations made in `viewDidLoad()` need no matching removal.

  • traitCollectionDidChange(_:) is still the current API for trait changes
  • Every rotation changes the horizontal size class
  • Inside viewWillTransition(to:with:), view.bounds already has the new size
  • Overriding viewWillTransition(to:with:) without calling super is harmless
  • Trait registrations must be removed in deinit or they leak

Assumes the iOS 27.1 SDK; registerForTraitChanges(_:handler:) and traitOverrides arrived in iOS 17, when traitCollectionDidChange(_:) was deprecated, and automatic trait tracking in layout callbacks is iOS 18.