获得当前界面方向的不同方法?

问题描述 投票:63回答:4

我知道三种获取当前界面方向的方法:

  • self.interfaceOrientation
  • [[UIApplication sharedApplication] statusBarOrientation]
  • [[UIDevice currentDevice] orientation]

它们之间有什么区别?

ios orientation
4个回答
112
投票

self.interfaceOrientation返回UIInterfaceOrientation,接口的当前方向。它是UIViewController中的一个属性,您只能在UIViewController类中访问此属性。

[[UIApplication sharedApplication] statusBarOrientation]返回UIInterfaceOrientation,即应用程序状态栏的当前方向。您可以在应用程序的任何位置访问该属性。我的经验表明,这是检索实际界面方向的更有效方法。

[[UIDevice currentDevice] orientation]返回UIDeviceOrientation,设备方向。您可以在应用程序的任何位置访问该属性。但是请注意,UIDeviceOrientation并不总是UIInterfaceOrientation。例如,当您的设备位于普通表上时,您会收到意外的值。


26
投票

[[UIApplication sharedApplication] statusBarOrientation]-它始终等于四个值之一:纵向,左横向,右横向和上下颠倒。

[[UIDevice currentDevice] orientation]-这个值等于标准的四个值,而且:未知,面朝上或面朝下。

[[UIApplication sharedApplication] statusBarOrientation]-是获得界面方向的首选方法。


1
投票

所有视图控制器都具有此功能

   override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
          //fromInterfaceOrientation.isLandscape
   }

或者您可以使用状态栏方向

   if UIApplication.sharedApplication().statusBarOrientation == UIInterfaceOrientation.Portrait {
        //
   }

在iOS 9中工作:)


0
投票

自iOS 13起]

您可以使用窗口场景的interfaceOrientation属性

UIWindow.windowScene.interfaceOrientation

let interfaceOrientation = UIApplication.shared.windows.first?.windowScene?.interfaceOrientation ?? UIInterfaceOrientation.unknown
© www.soinside.com 2019 - 2024. All rights reserved.