当设备方向改变时改变 ViewController?

Change ViewController when device orientation changes?

我想弄清楚如何在方向改变时切换 VC。我在同一个故事板中有 2 个不同的,portraitVC 和 landscapeVC。目标是在风景中发生本质上相同的事情,但使用不同的 UIImage。有人能帮忙吗?

逻辑应该是这样的:

if orientation is landscape {
    use landscapeVC 
} else {
    Use portraitVC
}

好的,我不太确定您要实现的目标,但这里有两种可能的解决方案:

1。在旋转时更改 UIImageView 图像

您可以添加一个观察者,以便在设备改变方向时得到通知。

将此添加到您的 viewDidLoad() 中:

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(didRotate), name: UIDeviceOrientationDidChangeNotification, object: nil)

方向改变时将调用以下函数:

func didRotate(notification: NSNotification) {
    if UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation) {
        // Change UIImageView image here
    }

    if UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation) {
        // Change UIImageView image here
    }
}

您可以使用此代码将图像更改为纵向或横向。哦!并且不要忘记在 viewWillDisappear():

中删除观察者
NSNotificationCenter.defaultCenter().removeObserver(self)

2。更改布局和 UI 旋转

这有点棘手,但一点也不难。您需要使用 Storyboard Size 类。

检查上图的中下部分。看看它说 wCompact hRegular 的地方,这意味着您为所有竖屏 iPhone 设计。对于横向 iPhone,使用 wAny hCompact。看到上图中的一些约束是如何被禁用的了吗?那是因为它们对特定大小 class 无效。

通过使用尺寸 类,您可以自定义 UI 不仅适用于纵向和横向,还适用于更具体的设备(iPhone 和 iPad)。您可以阅读有关此主题的更多信息 here

希望对您有所帮助! :)