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

Xcode: Disable rotation for a view in the ViewController.swift

我正在学习 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
    }

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

有两个视图控制器,link由 segue 编辑(并且都包装在 UINavigationController 中)。

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

var restrictRotation:UIInterfaceOrientationMask = .all

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

和viewWillAppear(因为它在我们遍历堆栈时被调用,所以比使用viewDidLoad更好)我们

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

第二个视图不会旋转。它只是一个标签。

在 viewDidLoad 中(您也可以使用 viewWillAppear)

override func viewDidLoad() {
    super.viewDidLoad()
    (UIApplication.shared.delegate as! AppDelegate).restrictRotation = .portrait
}

只使用故事板或代码没有区别,实现仍然是一样的。