当我旋转我的设备时,无论旋转如何,屏幕中间的红色方 block 都会移动并留在屏幕中央。但是,旋转设备时,the square does not immediately reposition itself, instead the previous location of the square can be seen until the rotation animation is fully complete.他们是否有一种方法可以让正方形在播放动画时立即重新定位,以便在旋转动画期间看不到它的旧位置?
import UIKit
class ViewController: UIViewController {
var square = UIView()
override func viewDidLoad() {
super.viewDidLoad()
square.isHidden = true
square = UIView(frame: CGRect(x: self.view.frame.width / 2 - 50, y: self.view.frame.height / 2 - 50, width: 100, height: 100))
square.backgroundColor = UIColor.red
self.view.addSubview(square)
square.isHidden = false
}
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
square.isHidden = true
square = UIView(frame: CGRect(x: self.view.frame.width / 2 - 50, y: self.view.frame.height / 2 - 50, width: 100, height: 100))
square.backgroundColor = UIColor.red
self.view.addSubview(square)
square.isHidden = false
}
}
最佳答案
两件事:
didRotate
早在 iOS 8 中就已弃用。它已被替换为viewWillTransition(to:with:)
。- 不要创建新的方 block 。只需更新原始正方形的框架即可。
下面的代码创建一个正方形并设置 autoresizingMask
使其保持居中。无需执行任何其他操作。当然,您也可以设置约束而不是 autoresizingMask
。
import UIKit
class ViewController: UIViewController {
var square: UIView!
override func viewDidLoad() {
super.viewDidLoad()
square = UIView(frame: CGRect(x: self.view.frame.width / 2 - 50, y: self.view.frame.height / 2 - 50, width: 100, height: 100))
square.backgroundColor = UIColor.red
square.autoresizingMask = [ .flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottonMargin ]
self.view.addSubview(square)
}
}
关于ios - 可以让屏幕上的元素立即旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48917013/