Swift高度变化的方向变化和uibutton隐藏在景观上

时间:2015-01-07 10:13:57

标签: iphone swift swift-extensions

我正在制作一个自定义键盘,其中当移动方向改变然后在风景中我必须隐藏一个按钮请建议我怎么做这个我使用下面的代码来完成这个任务请帮助我。 在横向也可以看到按钮我希望隐藏横向按钮并在纵向模式下可见

override func updateViewConstraints() {
    super.updateViewConstraints()

   //  Add custom view sizing constraints here

    var currentDevice: UIDevice = UIDevice.currentDevice()
    var orientation: UIDeviceOrientation = currentDevice.orientation

    if orientation.isLandscape {

     button.hidden = true
     }

    if orientation.isPortrait {
        button.hidden = false
     }
}

1 个答案:

答案 0 :(得分:1)

viewDidLoad放置

NSNotificationCenter.defaultCenter().addObserver(self, selector: "orientationChanged", name: UIDeviceOrientationDidChangeNotification, object: nil)

然后添加此方法

func orientationChanged()
{
    if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation))
    {            
        button.hidden = true
    }

    if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation))
    {
        button.hidden = false
    }

}

注意:

UIDevice.currentDevice().orientation可能无法为您提供正确的方向。您可以使用状态栏方向UIApplication.sharedApplication().statusBarOrientation

来自apple docs:

UIDevice.currentDevice().orientation

  

属性的值是一个表示当前值的常量   设备的方向。该值代表物理   设备的方向可能与当前不同   应用程序用户界面的方向。看到   “UIDeviceOrientation”用于描述可能的值。