【问题标题】:Xcode: Disable rotation for a view in the ViewController.swiftXcode:在 ViewController.swift 中禁用视图的旋转
【发布时间】:2019-04-10 22:52:16
【问题描述】:

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

【问题讨论】:

标签: ios swift xcode10.2


【解决方案1】:

我认为上面@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
}

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

【讨论】:

  • 哇。非常感谢你的例子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多