关于ios:Xcode:在ViewController.swift中禁用视图旋转

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

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

我不希望视图每次旋转。

到目前为止我有这个。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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提供的链接是您所需要的。为了提供帮助,我实现了一个小示例项目。

有两个视图控制器,由一个segue链接(都package在UINavigationController中)。

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

1
2
3
4
5
6
var restrictRotation:UIInterfaceOrientationMask = .all

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

enter

和viewWillAppear(因为遍历堆栈时会调用它,因此比使用viewDidLoad更好),我们

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

第二个视图将不会旋转。它只是带有标签。
enter

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

仅使用情节提要或代码没有区别,实现仍将相同。