【发布时间】:2016-02-26 01:34:47
【问题描述】:
我正在创建一个 iPhone 应用程序,它的图标下方带有文本标签。我希望在手机旋转到横向模式时隐藏标签,因为它们没有足够的空间。最简单的方法是什么?
【问题讨论】:
我正在创建一个 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
}
}
【讨论】:
如果您想为更改设置动画(例如淡出标签或其他动画),您实际上可以通过覆盖 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
【讨论】:
Objective 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...
}
}
【讨论】: