2016-02-26 35 views
0

我正在创建一个iPhone应用程序,其中包含带有文本标签的图标。我希望手机旋转到横向模式时隐藏标签,因为它们没有足够的空间。什么是最简单的方法来做到这一点?手机处于横向模式时隐藏标签

回答

1

您可以先在viewDidLoad中添加一个NSNotification以了解设备的方向更改。

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

这将调用函数“旋转”时,设备知道它的方向改变了,那么你只需要创建一个函数,并把我们的代码里面。

func rotated() 
{ 
    if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation)) 
    {    
     print("landscape") 
     label.hidden = true 
    } 

    if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation)) 
    { 
     print("Portrait") 
     label.hidden = false 
    } 

} 

解决方案从"IOS8 Swift: How to detect orientation change?"

+0

完美工作,谢谢! –

+0

不客气:) – Lee

1

得到,如果你想进行动画处理的变化(例如淡出的标签,或其他一些动画),实际上你可以做到这一点与通过重写viewWillTransitionToSize方法旋转同步例如

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

coordinator.animateAlongsideTransition({ (UIViewControllerTransitionCoordinatorContext) -> Void in 

    let orient = UIApplication.sharedApplication().statusBarOrientation 

    switch orient { 
    case .Portrait: 
     println("Portrait") 
     // Show the label here... 
    default: 
     println("Anything But Portrait e.g. probably landscape") 
     // Hide the label here... 
    } 

    }, completion: { (UIViewControllerTransitionCoordinatorContext) -> Void in 
     println("rotation completed") 
}) 

super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) 
} 

以上内容来自于以下的答案必须采取的代码示例:https://stackoverflow.com/a/28958796/994976

0

目标C版

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)orientation duration:(NSTimeInterval)duration 
{ 
    if (UIInterfaceOrientationIsPortrait(orientation)) 
    { 
     // Show the label here... 
    } 
    else 
    { 
     // Hide the label here... 
    } 
} 

斯威夫特版本

override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) 
{ 
    if (UIInterfaceOrientationIsPortrait(toInterfaceOrientation)) 
    { 
     // Show the label here... 
    } 
    else 
    { 
     // Hide the label here... 
    } 
} 
相关问题