1

I have a tool pane which in compact H mode, will be at the bottom spanning the full screen, but in compact V mode (or non compact H mode), it will be on the right as a floating pane. How do I get the target UITraitCollection + the target size? They seem to be in 2 different methods:

    override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
        // need size rect
    }

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        // need traits
    }

I need both infos for animating things properly! Thanks so much!

Pranav Kasetti
  • 8,770
  • 2
  • 50
  • 71
Mike S
  • 4,092
  • 5
  • 35
  • 68

1 Answers1

0

You can in fact get both values, the size and the trait collection in both methods, by operating on the UIViewControllerTransitionCoordinator.

let didQueueAnimation = coordinator.animate(alongsideTransition: { context in
    guard let view = context.view(forKey: UITransitionContextViewKey.to) else { 
        return
    }
    let newScreenSize = view.frame.size
    guard let viewController = context.viewController(forKey: UITransitionContextViewKey.to) else { 
        return
    }
    let newTraitCollection = viewController.traitCollection // <-- New Trait Collection
    // You can also get the new view size from the VC:
    // let newTraitCollection = viewController.view.frame.size

    // Perform animation if trait collection and size match.

}, completion: { context in
    // Perform animation cleanup / other pending tasks.
})

if (didQueueAnimation) {
    print("Animation was queued.")
}

Apple's idea here is to simplify the call site with one context parameter that can be queried for multiple properties, and also execute asynchronously so that the values for the final transitioned view or VC can be fetched accurately in one place even before the update occurs.

While you can perform animations in either of the WillTransition methods, I would use the coordinator.animate(alongsideTransition:completion:) method if possible rather than coordinator.notifyWhenInteractionChanges(_:) since it synchronizes the system animation alongside your own custom animation and you can still query the context for the new traitCollection or frame.size using the techniques above.

Pranav Kasetti
  • 8,770
  • 2
  • 50
  • 71