gpt4 book ai didi

ios - 可以让屏幕上的元素立即旋转

转载 作者:行者123 更新时间:2023-11-28 15:00:57 25 4
gpt4 key购买 nike

当我旋转我的设备时,无论旋转如何,屏幕中间的红色方 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
}
}

最佳答案

两件事:

  1. didRotate 早在 iOS 8 中就已弃用。它已被替换为 viewWillTransition(to:with:)
  2. 不要创建新的方 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com