可以让屏幕元素立即旋转

时间:2018-02-21 23:04:06

标签: ios swift uiviewcontroller uikit

当我旋转设备时,无论旋转如何,屏幕中间的红色方块都会移动到屏幕中央。但是,在旋转设备时,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
    }
}

1 个答案:

答案 0 :(得分:1)

两件事:

  1. didRotate在iOS 8中被弃用了。它已被viewWillTransition(to:with:)取代。
  2. 不要创建新的方块。只需更新原始方块的框架即可。
  3. 下面的代码会创建一个方格并设置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)
        }
    }