【问题标题】:iOS viewWillTransitionToSize and device orientationiOS viewWillTransitionToSize 和设备方向
【发布时间】:2015-05-03 11:06:06
【问题描述】:

我正在使用 viewWillTransitionToSize 来检测设备何时旋转为横向。根据目标大小,我可以检测是否朝向横向并根据需要调整我的特征...

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {

    if size.width > size.height {
        self.setOverrideTraitCollection(UITraitCollection(horizontalSizeClass: UIUserInterfaceSizeClass.Regular), forChildViewController: viewController)
    }
    else{
        self.setOverrideTraitCollection(nil, forChildViewController: viewController)
    }

    super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
}

但是,我希望能够检测到我的设备是否正在转换为横向左侧或横向右侧。这将允许我根据设备的特定方向创建不同的行为或视图。 (左或右)。

不使用任何不推荐使用的功能是否可以做到这一点?

我想过使用状态栏方向...

    let orientation = UIApplication.sharedApplication().statusBarOrientation;
    if( orientation == UIInterfaceOrientation.LandscapeLeft )
    {
        // Do something
    }
    else if( orientation == UIInterfaceOrientation.LandscapeRight )
    {
        // Do something else
    }

...但这无济于事,因为这似乎给出了“旧”状态方向。

如何获取具体的目标方向?

【问题讨论】:

    标签: ios iphone orientation screen-orientation size-classes


    【解决方案1】:

    使用[UIDevice currentDevice].orientation

    【讨论】:

    • UIInterfaceOrientation 是相关的枚举,而不是 UIDeviceOrientation。
    【解决方案2】:

    您可以在旋转使用UIViewControllerTransitionCoordinator时获取方向,如下所示:

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
    
        // will execute before rotation
    
        coordinator.animate(alongsideTransition: { (context: UIViewControllerTransitionCoordinatorContext) in
    
            // will execute during rotation
            let orientation = UIApplication.shared.statusBarOrientation
            if orientation == .landscapeLeft 
            {
                // Do something
            } 
            else if orientation == .landscapeRight 
            {
                // Do something else
            }
        }) { (context: UIViewControllerTransitionCoordinatorContext) in
            // will execute after rotation
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-24
      相关资源
      最近更新 更多