【问题标题】:How to know the current orientation of a iDevice如何知道 iDevice 的当前方向
【发布时间】:2019-12-28 17:01:04
【问题描述】:

我正在为数学课程和练习做一个应用程序......

我只编写了 MainMenu,但我遇到了问题。 事实上,我想知道当前的方向来设置我的东西。

但是,我尝试了不同的方法来了解当前的方向,但我没有成功:

if UIDevice.current.orientation == UIDeviceOrientation.portrait {
            NSLog("Portrait")

        }

        else if UIDevice.current.orientation == UIDeviceOrientation.landscapeRight || UIDevice.current.orientation == UIDeviceOrientation.landscapeRight {
            NSLog ("Landscape")
        }

我也看到了这个答案,但它不起作用(或者我可能不太了解):Getting device orientation in Swift,bu

我想在 ViewDidLoad() 中指定我在 UIViewController 中。

感谢您的帮助????‍????

【问题讨论】:

  • 覆盖函数viewDidLayoutSubviews()

标签: ios swift xcode uikit


【解决方案1】:

我设置了一个带有按钮的小型原型应用程序,该按钮在按下时检查设备方向的变化。这是documentation 的链接,希望能帮助您进一步推进您的项目。

class ViewController: UIViewController {

    let device = UIDevice.current

    override func viewDidLoad() {
        super.viewDidLoad()
        device.beginGeneratingDeviceOrientationNotifications()
    }

    @IBAction func orientation(_ sender: UIButton) {
        if device.isGeneratingDeviceOrientationNotifications {
            switch device.orientation {
            case .landscapeLeft:
                print("Landscape Left")
            case .portrait:
                print("Portrait")
            case .landscapeRight:
                print("Right")
            case .portraitUpsideDown:
                print("Upside down")
            case .unknown:
                print("Unknown")
            default:
                print("Else")
            }
        }
    }
}

【讨论】:

  • 这太过分了。他没有获得方向的原因是(实际上他正在获得 UIDeviceOrientation.unknown)他正在 viewDidLoad 中尝试。
  • 同意,但他们似乎不知道代码,所以我把它写了出来。您在上面的评论也是一种无需任何用户输入即可获得通知的更好方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多