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

标签 ios swift xcode10.2

我正在学习在 Xcode 中编写 View ,而不是使用 .storyboard

我不希望 View 在旋转时旋转。

到目前为止我有这个。

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 提供的链接是您需要的。为了提供帮助,我实现了一个小示例项目。

有两个 View Controller ,由一个 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
}

第二个 View 不会旋转。它只是一个标签。 enter image description here

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

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

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

关于ios - Xcode : Disable rotation for a view in the ViewController. swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55622364/

相关文章:

swift - 谁能解释 Swift Combine 的 Subject.eraseToAnySubject() 方法以及应该在哪里使用它?

json - Alamofire 通过数组索引进行解码

ios - iOS 应用程序的相机、麦克风和音频/视频存储权限

iphone - 如何修改UIDatePicker的内容?

ios - 如何指定同类型的 UIGestureRecognizer 的优先级?

ios - 重写 ManageObjectContext - 数据消失

ios - iOS8 中 UITextField 默认的 borderColor 是什么?

ios - 此 libswiftCore.dylib 副本需要 12.2.0 之前的操作系统版本

ios - 确定用户是否在我的 iOS 应用程序中授予了对 "Motion and Fitness"权限的访问权限