如何在iOS中修复错误的状态栏方向
当我第一次启动iOS时,当时是iOS 8,我有一个错误花了整整一天的时间才弄清楚。 问题是,尽管我已经将主ViewController
锁定为纵向模式,但状态栏始终会定向为设备定向。 这就是为什么我在GitHub上启动notes项目的原因,该项目详细说明了我所面临的问题。
ViewController已锁定为人像,但设备旋转时状态栏也会旋转·问题2•
问题rootViewController被锁定为纵向。 当我旋转时,视图控制器为纵向,但状态为… github.com
现在是iOS 12,令我惊讶的是人们仍然遇到这个问题。 今天,我将在iOS 12项目中修订此问题并使用Swift。
支持的界面方向
大多数应用仅支持纵向模式,横向或横向有1或2个屏幕可用于图像查看或视频播放器。 因此,我们通常声明纵向,横向左和横向右。
从iOS 7开始,应用具有简单的设计,着重于内容。 UIViewController
在外观规范中被赋予了更大的作用。
假设我们有一个MainViewController
作为rootViewController
,我们希望将其锁定为纵向模式。
@UIApplicationMain
类AppDelegate:UIResponder,UIApplicationDelegate {
var window:UIWindow?
func application(_ application:UIApplication,didFinishLaunchingWithOptions launchOptions:[UIApplication.LaunchOptionsKey:Any]?)->布尔{
窗口= UIWindow(框架:UIScreen.main.bounds)
window?.rootViewController = MainViewController()
窗口?.makeKeyAndVisible()
返回真
}
}
我们可以在Info.plist
指定一个名为UIViewControllerBasedStatusBarAppearance的属性,以断言我们希望UIViewController
动态控制状态栏的外观。
一个布尔值,指示状态栏外观是否基于当前视图控制器的首选样式。
首先在Info.plist中进行声明
UIViewControllerBasedStatusBarAppearance
然后在MainViewController
,将状态栏锁定为纵向
导入UIKit
类MainViewController:UIViewController {
让标签= UILabel()
覆盖func viewDidLoad(){
super.viewDidLoad()
view.backgroundColor = .yellow
label.textColor = .red
label.text =“ MainViewController”
label.font = UIFont.preferredFont(forTextStyle:.headline)
label.sizeToFit()
view.addSubview(label)
}
覆盖func viewDidLayoutSubviews(){
super.viewDidLayoutSubviews()
label.center = CGPoint(x:view.bounds.size.width / 2,y:view.bounds.size.height / 2)
}
覆盖var supportInterfaceOrientations:UIInterfaceOrientationMask {
返回.portrait
}
}
这样的想法是,无论设备的方向如何,状态栏始终保持纵向模式,与MainViewController
相同。
但是令我惊讶的是,事实并非如此! 如您在下面的屏幕快照中所见,MainViewController是纵向的,但状态栏不是。
停止混合代码和情节提要
我花了一段时间才弄清楚,在我用代码声明UIWindow
同时,我还有MainStoryboard来配置UIWindow
UIMainStoryboardFile
主要
而且Storyboard中的UIWindow
具有默认的根ViewController
导入UIKit
类ViewController:UIViewController {
覆盖func viewDidLoad(){
super.viewDidLoad()
}
}
UIViewControllerBasedStatusBarAppearance的含义
在iOS中,状态栏默认情况下隐藏在横向中。
- 将
UIViewControllerBasedStatusBarAppearance
设置为false意味着我们想要这种默认行为 - 将
UIViewControllerBasedStatusBarAppearance
设置为true意味着我们要控制状态栏的外观。 因此,要隐藏状态栏,我们必须在rootViewController
,所显示的视图控制器或全屏视图控制器中重写prefersStatusBarHidden
如您所见,问题在于Storyboard中UIWindow
中的ViewController
与我们的MainViewController
在代码中发生了冲突,因此造成了很多混乱。
解决方案很简单,删除Main.storyboard
,不要在项目中使用它
UIMainStoryboardFile
主要
现在我们获得了所需的行为,无论设备的方向如何,状态栏和视图控制器始终锁定为纵向。
如果您使用像我这样的代码来设置UI,请记住清理Xcode生成项目时默认生成的情节提要和ViewController
。