手机处于横向模式时隐藏标签

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

您可以先在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:如何检测方向变化?”

如果要为更改设置动画(例如淡出标签或其他动画),您实际上可以通过覆盖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 eg probably landscape") // Hide the label here... } }, completion: { (UIViewControllerTransitionCoordinatorContext) -> Void in println("rotation completed") }) super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) } 

以上代码示例取自以下答案: https : //stackoverflow.com/a/28958796/994976

目标C版

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

Swift版本

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