I am creating an iPhone app which has icons with text labels underneath. I want the labels to be hidden when the phone is rotated to landscape mode, as there is not enough space for them. What is the easiest way to do this?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You can first add an NSNotification to know orientation change on your device in viewDidLoad.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "rotated", name: UIDeviceOrientationDidChangeNotification, object: nil)
This will call the function "rotated" when device know it's orientation changed, then you just have to create that function and put ur code inside.
func rotated()
{
if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation))
{
print("landscape")
label.hidden = true
}
if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation))
{
print("Portrait")
label.hidden = false
}
}
Solution get from "IOS8 Swift: How to detect orientation change?"
回答2:
If you want to animate the change (e.g. fade out the label, or some other animation), you can actually do that in sync with the rotation by overriding the viewWillTransitionToSize
method e.g.
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)
}
Above code sample taken from the following answer: https://stackoverflow.com/a/28958796/994976
回答3:
Objective C Version
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)orientation duration:(NSTimeInterval)duration
{
if (UIInterfaceOrientationIsPortrait(orientation))
{
// Show the label here...
}
else
{
// Hide the label here...
}
}
Swift Version
override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval)
{
if (UIInterfaceOrientationIsPortrait(toInterfaceOrientation))
{
// Show the label here...
}
else
{
// Hide the label here...
}
}