【问题标题】:Detect device orientation in Init function在 Init 函数中检测设备方向
【发布时间】:2016-09-06 15:18:06
【问题描述】:

我正在使用这些代码行检测设备方向:

UIDevice.currentDevice().orientation.isPortrait.boolValue
UIDevice.currentDevice().orientation.isLandscape.boolValue

我用这段代码检测它是否是 iPad:

userInterfaceIdiom == .Pad

我在commonInit() 函数中使用了这段代码,该函数在Init() 函数中调用。当我在 iPad 上执行我的代码时,前两行都返回 false,这是不正确的,其中一个应该是 true。第三行工作正常。

如果我在其他函数中使用该代码,例如supportedInterfaceOrientations(),它可以正常工作。你知道可能是什么问题吗?

【问题讨论】:

  • init()... init()...,我们在说谁的init()方法?
  • 我尝试使用代码行的类的 init() 方法。我想用取决于 iPad 方向的值来初始化类
  • @holex 要求提供类的 type ......它是 UIViewController 吗?在构建此类之前,应用程序是否已完全初始化并告诉 AppDelegate 它已准备好?

标签: ios swift ipad landscape-portrait


【解决方案1】:

您可能忽略了此文档:

您还可以使用 UIDevice 实例来检测设备的变化 特征,例如物理方向。你得到当前 使用方向属性的方向或接收更改 通过注册通知 UIDeviceOrientationDidChangeNotification 通知。 使用前 要获取方向数据,您必须启用这些技术中的任何一种 使用 beginGeneratingDeviceOrientationNotifications 传送数据 方法。当您不再需要跟踪设备方向时,请致电 endGeneratingDeviceOrientationNotifications 方法禁用 发送通知。

此外,这是一个 3-D 方向。你可能不想要那个。 orientation 属性的实际值是多少?见:

enum UIDeviceOrientation : Int {
    case Unknown
    case Portrait
    case PortraitUpsideDown
    case LandscapeLeft
    case LandscapeRight
    case FaceUp
    case FaceDown }

你真正想要的可能在这里: "interfaceOrientation" is deprecated in iOS 8, How to change this method Objective C

有时 TraitCollections 并不能满足您的所有设计需求。为了 在这些情况下,Apple 建议比较视图的边界:

如果 view.bounds.size.width > view.bounds.size.height { // ... }

【讨论】:

    猜你喜欢
    • 2023-03-09
    • 2013-10-29
    • 2011-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 2021-12-29
    相关资源
    最近更新 更多