在iOS 5中,我们可以通过编程方式来更改设备的方向:
[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeRight];
但在 iOS 6 中,setOrientation
已被弃用,我该如何在编程中更改设备方向?
在iOS 5中,我们可以通过编程方式来更改设备的方向:
[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeRight];
但在 iOS 6 中,setOrientation
已被弃用,我该如何在编程中更改设备方向?
@implementation UINavigationController (自动旋转)
-(NSUInteger)supportedInterfaceOrientations
{
//make the check for iphone/ipad here
if(IPHONE)
{
return UIInterfaceOrientationMaskPortrait;
}
else
{
return UIInterfaceOrientationMaskLandscape;
}
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationPortrait;
}
- (BOOL)shouldAutorotate
{
return NO;
}
if (self.interfaceOrientation != UIInterfaceOrientationLandscapeRight) {
// https://dev59.com/KnVC5IYBdhLWcg3wykej
// http://openradar.appspot.com/radar?id=697
// [[UIDevice currentDevice] setOrientation: UIInterfaceOrientationLandscapeRight]; // Using the following code to get around apple's static analysis...
[[UIDevice currentDevice] performSelector:NSSelectorFromString(@"setOrientation:") withObject:(id)UIInterfaceOrientationLandscapeRight];
}
performSelector
上的(潜在)泄漏并不重要。只要分配一个有效的选择器,它就永远不会泄漏。 - n00bProgrammer这对我在Xcode 6和5上都有效。
- (BOOL)shouldAutorotate {return YES;}
- (NSUInteger)supportedInterfaceOrientations {return (UIInterfaceOrientationMaskPortrait);}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return NO;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return interfaceOrientation == UIInterfaceOrientationPortrait
|| interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown ;
}
有趣的是,其他人在不设置类似于这样的东西之后并没有遇到问题:
+ (void)setOrientation:(UIDeviceOrientation)orientation {
[UIDevice.currentDevice setValue:@(orientation) forKey:@"orientation"];
[UIViewController attemptRotationToDeviceOrientation];
[UIDevice.currentDevice setValue:@(UIDeviceOrientationUnknown) forKey:@"orientation"];
}