首页 > 解决方案 > 如何获取目标 UITraitCollection 以及目标 rect

问题描述

我有一个工具窗格,在紧凑型 H 模式下,它将位于整个屏幕的底部,但在紧凑型 V 模式(或非紧凑型 H 模式)下,它将作为浮动窗格位于右侧。如何获得目标 UITraitCollection + 目标大小?他们似乎有两种不同的方法:

    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
    }

我需要这两个信息来正确设置动画!非常感谢!

标签: swiftuikituitraitcollection

解决方案


实际上,您可以通过对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 的想法是使用一个可以查询多个属性的上下文参数来简化调用站点,并且还可以异步执行,以便即使在更新发生之前,也可以在一个位置准确获取最终转换视图或 VC 的值。

虽然您可以在任何一种WillTransition方法中执行动画,但如果可能,我会使用该coordinator.animate(alongsideTransition:completion:)方法,而不是coordinator.notifyWhenInteractionChanges(_:)因为它将系统动画与您自己的自定义动画同步,您仍然可以查询context新的traitCollectionframe.size使用上述技术。


推荐阅读