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

标签 ios swift uiviewcontroller uikit

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

相关文章:

android - 如果我给出像文件夹名称/图片名称这样的图像路径,它会显示在 Windows 平台上,但不会显示在 xamarin 的 Android 中

ios - MSMessageLayout 在 iMessage 应用程序中没有成员标题

ios - 我在 CollectionViewCell 中有一个 UIButton,它又在 TableViewCell 中。如何通过单击 UIButton 导航到下一个 View Controller ?

ios - 纹理图集可以包含 PDF 图像吗?

ios - 接口(interface)构建器约束错误

swift - 设置高度: TableViewCells with custom Nib that are different sizes

ios - UISegmentedControl 以编程方式

ios - 如何使用 iOS 在 Storyboard 上创建 ImageView 中心?

ios - Siri 与自定义意图的集成面临问题

iOS 如何从 UIViewController 访问 UIView 属性