当 UIViewController
出现时,我需要创建动画(从左上角 10 到屏幕中间)。
我为此使用了 CGRect 框架,但是当我在加载 View 后旋转屏幕时,动画 View 会失败,因为动画完成后 View 需要居中对齐。
我也尝试过使用自动布局,但它并不能使 UIImageView
每次都进行动画处理。
这是我当前正在使用的代码。
override func viewDidLoad() {
super.viewDidLoad()
imgView.frame = CGRect(x: 10, y: 10, width: 80, height: 80)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIView.animate(withDuration: 2.0, animations: {
self.imgView.frame = CGRect(x: (self.view.frame.width / 2) - 40, y: (self.view.frame.height / 2) - 40, width: 80, height: 80)
}) { (success) in
}
}
最佳答案
要在方向更改期间获得正确的 self.view.frame.width
大小,您应该重写 viewWillTransition(..)
方法:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
// here you have the right size.width
}
关于iOS 图像帧动画在 Swift 中无法在设备方向上获得正确的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57399442/