Xcode:在ViewController.swift中禁用视图的旋转

4

我正在学习在Xcode中编程视图,而不是使用.storyboard

我不希望视图在旋转时随之旋转。

到目前为止,我已经做到了这一点。

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.backgroundColor = .white

        let imageView = UIImageView(image: #imageLiteral(resourceName: "facebook_logo.png"))
        view.addSubview(imageView)


        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        imageView.topAnchor.constraint(equalTo: view.topAnchor, constant: 300).isActive = true
        imageView.widthAnchor.constraint(equalToConstant: 100).isActive = true
        imageView.heightAnchor.constraint(equalToConstant: 100).isActive = true
    }

2
看起来这里的答案可以满足您的需求:https://dev59.com/XVkT5IYBdhLWcg3wK8hT#52221671 - oaccamsrazor
我不确定这是否是我正在寻找的内容。如果设备旋转,视图不会旋转。 - Miguel Yurivilca
1个回答

8

我认为@oaccamsrazer提供的链接是您需要的。为了帮助您,我实现了一个小的示例项目。

有两个视图控制器,由一个segue连接(并且都包装在UINavigationController中)。

在AppDelegate中,您需要以下内容:

var restrictRotation:UIInterfaceOrientationMask = .all

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask
{
    return self.restrictRotation
}

enter image description here

当我们遍历堆栈时,由于viewWillAppear被调用,因此比使用viewDidLoad更好。

override func viewWillAppear(_ animated: Bool) {
    (UIApplication.shared.delegate as! AppDelegate).restrictRotation = .all
}

第二个视图不会旋转。它只有一个标签。 enter image description here 在viewDidLoad中(也可以使用viewWillAppear)。
override func viewDidLoad() {
    super.viewDidLoad()
    (UIApplication.shared.delegate as! AppDelegate).restrictRotation = .portrait
}

使用Storyboard或者代码实现都没有区别,最终的结果都是相同的。


哇,非常感谢您提供的示例。 - Miguel Yurivilca

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接