设备方向更改时更改ViewController?

问题描述 投票:1回答:1

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

逻辑应该是这样的:

if orientation is landscape {
    use landscapeVC 
} else {
    Use portraitVC
}
ios swift viewcontroller
1个回答
1
投票

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

1. Change the UIImageView image on rotation

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

将其添加到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. Change the layout and UI on rotation

这有点棘手,但并不困难。您需要使用Storyboard Size Classes。

Compact x Regular Size Class

检查上图中下部分。看看wCompact hRegular的位置,这意味着你要设计所有的纵向iPhone。对于横向的iPhone,请使用wAny hCompact。看看如何禁用上图中的某些约束?那是因为它们对特定的大小类没有效果。

Any x Compact Size Class

通过使用大小类,您不仅可以为纵向和横向自定义UI,还可以为更具体的设备(iPhone和iPad)自定义UI。你可以阅读更多关于这个主题here的信息。

我希望这有帮助! :)

© www.soinside.com 2019 - 2024. All rights reserved.