我正在制作一个自定义键盘。我想根据视图的宽度和高度生成键(UIButtons)的宽度和高度。
最初加载键盘时,viewDidAppear 正确确定了视图的高度。(375 x 216)
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.renderKeys()
}
当旋转到横向时,它会调用 viewWillTransition
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
NSLog("toSize \(size.width) x \(size.height)")
coordinator.animate(alongsideTransition: {(_ context: UIViewControllerTransitionCoordinatorContext) -> Void in
NSLog("animating \(self.view.frame.width) x \(self.view.frame.height)")
}, completion: {(_ context: UIViewControllerTransitionCoordinatorContext) -> Void in
NSLog("animationCompleted \(self.view.frame.width) x \(self.view.frame.height)")
self.renderKeys()
})
}
旋转回纵向会导致此结果。
我发现 viewWillTransition 的大小不能正确确定视图的大小,或者我只是误解了该函数的用法。即使在动画之后,我也无法获得正确的视图宽度和高度。
这是按顺序排列的调试日志。
[28651:1348399] Calling viewDidAppear
[28651:1348399] Cleaning keys
[28651:1348399] toSize 667.0 x 216.0
[28651:1348399] animating 667.0 x 216.0
[28651:1348399] animationCompleted 667.0 x 216.0
[28651:1348399] Cleaning keys
[28651:1348399] toSize 375.0 x 162.0
[28651:1348399] animating 375.0 x 162.0
[28651:1348399] animationCompleted 375.0 x 162.0