在iOS中锁定/解锁屏幕方向变化

3

我正在开发一个iOS应用程序。我需要通过按钮单击来锁定或解锁方向。

我已经查看了这个链接

我需要在单击按钮时锁定屏幕,如果再次单击则需要解锁。

我尝试使用这段代码,但没有什么用。

- (BOOL)shouldAutorotateToInterfaceOrientation:
(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
            interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}


-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationPortrait | UIInterfaceOrientationLandscapeLeft | UIInterfaceOrientationLandscapeRight |UIInterfaceOrientationPortraitUpsideDown;
}

非常感谢您的帮助。


我不知道苹果是否已经解决了这个问题,但 shouldAutoRotateToInterfaceOrientation 在 IOS 5 中运行得非常完美,在 IOS6 及以后版本中则变得完全无用。由于我无法从页面到页面控制它,最终我对整个应用程序的方向进行了修复。如果这个问题已经解决,我会很高兴知道。 - Paulo
1
@ paulo,不是它不起作用,从iOS 6开始,应使用supportedInterfaceOrientations。 - Pochi
从iOS 6开始,方向更改依赖于容器控制器,如导航控制器或选项卡控制器。您可以覆盖容器控制器方法,逐页控制方向更改。参考此处 - Anil Varghese
你期望的行为是什么?按下按钮立即旋转屏幕吗?锁定另一个屏幕的方向?整个应用程序都锁定方向?这不是设备上锁定按钮的作用吗? - Pochi
@Chiquis 对于整个应用程序,我需要锁定屏幕。当按钮被点击时,它不应旋转,如果我再次点击它,则应旋转。锁定按钮意味着 PUSH 按钮需要为此提供功能。 - KethanKumar
2个回答

2
如果您想在按钮点击时仅锁定旋转,则可以使用以下方法。
- (BOOL)shouldAutorotate
{
   if (autorotate) {
     return YES;
   } 
   else
   {
     return NO;
   }
}

因为 shouldAutorotateToInterfaceOrientation 已经过时了。

使用此方向将被锁定在当前方向。


被弃用并不意味着它不应该被实现,而是意味着如果他计划仅支持iOS 6+,那么它就不需要了,否则他必须实现shouldAutorotateToInterfaceOrientation以支持之前的iOS版本。 - Pochi
@Chiquis 是的,你说得对。但如果你想支持iOS6+,那么这不会适用于你。iOS 6 还有一个问题,在 iOS 6 中,方向不支持导航,在这种情况下,你必须覆盖方向。 - Gourav Gupta
我的意思是,如果你想支持最广泛的iOS版本,那么你应该同时实现两者。我不理解关于iOS 6不支持导航的部分。 - Pochi

1
我发现了一些有趣的东西,你可以这样做来锁定旋转:

[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];

然后再重新启用:

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

非常简单。
在真实的 iPhone 设备上测试过,版本为 7.1.1。文档显示自 iOS 2.0 起可用,因此应该适用于所有设备。
参考: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIDevice_Class/Reference/UIDevice.html#//apple_ref/occ/instm/UIDevice/endGeneratingDeviceOrientationNotifications

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