如何在iOS 6中通过编程方式更改设备方向

46

iOS 5中,我们可以通过编程方式来更改设备的方向:

[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeRight];

但在 iOS 6 中,setOrientation 已被弃用,我该如何在编程中更改设备方向?


请查看此链接:https://dev59.com/mm855IYBdhLWcg3wc0Dy#4331014 - Bala
3
最好您能接受答案。这将提高您的采纳率。 - Dinesh Raja
Swift 4: -> https://dev59.com/61wY5IYBdhLWcg3wq5Xk#51036885Swift 4 是苹果公司发布的一种编程语言,用于开发 iOS、macOS、watchOS 和 tvOS 应用程序。它具有许多新特性和改进,例如 Codable 协议、原生字符串、强大的错误处理机制等。如果你是一名 iOS 或 macOS 开发者,学习 Swift 4 肯定会使你受益匪浅。 - Jack
15个回答

2

@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;
 }

1
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];
}

在iOS7中不起作用,还会触发“PerformSelector可能会导致泄漏,因为其选择器未知”警告。 - Lukasz 'Severiaan' Grela
1
这个解决方案已经不再有效了。你是对的。 然而,在performSelector上的(潜在)泄漏并不重要。只要分配一个有效的选择器,它就永远不会泄漏。 - n00bProgrammer

0

这对我在Xcode 6和5上都有效。

- (BOOL)shouldAutorotate {return YES;}
- (NSUInteger)supportedInterfaceOrientations {return (UIInterfaceOrientationMaskPortrait);}

0
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{
    // Return YES for supported orientations
   return NO;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
   return  interfaceOrientation == UIInterfaceOrientationPortrait
           || interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown ;
}

0

有趣的是,其他人在不设置类似于这样的东西之后并没有遇到问题:

+ (void)setOrientation:(UIDeviceOrientation)orientation {
    [UIDevice.currentDevice setValue:@(orientation) forKey:@"orientation"];
    [UIViewController attemptRotationToDeviceOrientation];
    [UIDevice.currentDevice setValue:@(UIDeviceOrientationUnknown) forKey:@"orientation"];
}

我的要求是能够强制旋转方向,然后再旋转到设备的自然方向...有UIDeviceOrientationDidChangeNotification可以获取设备需要旋转回哪个方向的信息,但如果在UIDevice中更改方向后不立即设置为未知,则它实际上部分无法工作。还有更多细节可以让它变得很酷,但会留下来,因为它超出了这个简单问题的范围。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接