如何使用Swift锁定仅主视图的肖像方向 [英] how to lock portrait orientation for only main view using swift
问题描述
我已经使用 swift 为iPhone创建了一个应用程序,该应用程序由嵌入在导航控制器中的许多视图组成.我想将主视图锁定为纵向,而将导航控制器的子视图锁定为横向. 这是我的意思的示例:
I have created an application for iPhone, using swift, that is composed from many views embedded in a navigation controller. I would like to lock the main view to Portrait orientation and only a subview of a navigation controller locked in Landscape orientation. Here is an example of what i mean:
- UINavigationController
- UiViewController1(纵向锁定)初始视图控制器,在导航栏上放置一个按钮,使用户可以访问列表,在列表中可以选择其他视图
- UIViewController2(锁定为横向模式)
- UiViewController3(纵向和横向)
- UiViewController4(纵向和横向)
- ...
- ...
- UINavigationController
- UiViewController1 (Locked in Portrait) Initial view controller with a button placed on the navigation bar that give to the user the possibility to access to a lists where can be selected other views
- UIViewController2 (Locked in Landscape)
- UiViewController3 (Portrait and Landscape)
- UiViewController4 (Portrait and Landscape)
- ...
- ...
我该怎么做?
推荐答案
According to the Swift Apple Docs for
supportedInterfaceOrientations
:讨论
当用户更改设备方向时,系统会在填充窗口的根视图控制器或最上面显示的视图控制器上调用此方法.如果视图控制器支持新的方向,则将窗口和视图控制器旋转到新的方向.仅当视图控制器的shouldAutorotate方法返回true时,才调用此方法.
Discussion
When the user changes the device orientation, the system calls this method on the root view controller or the topmost presented view controller that fills the window. If the view controller supports the new orientation, the window and view controller are rotated to the new orientation. This method is only called if the view controller's shouldAutorotate method returns true.
您的导航控制器应覆盖
shouldAutorotate
和supportedInterfaceOrientations
,如下所示.为了方便起见,我在UINavigationController
扩展程序中做到了这一点:Your navigation controller should override
shouldAutorotate
andsupportedInterfaceOrientations
as shown below. I did this in aUINavigationController
extension for ease:extension UINavigationController { public override func shouldAutorotate() -> Bool { return true } public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return (visibleViewController?.supportedInterfaceOrientations())! } }
您的主视图控制器(始终为肖像)应该具有:
And your main viewcontroller (portrait at all times), should have:
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.Portrait }
然后,在您的子视图控制器中要支持纵向或横向:
Then, in your subviewcontrollers that you want to support portrait or landscape:
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.All }
已针对iOS 9更新:-)
这篇关于如何使用Swift锁定仅主视图的肖像方向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!