1

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

1 回答 1

3

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

有两个视图控制器,由 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
}

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

于 2019-04-11T08:07:18.760 回答