iOS 6.0限制导航控制器内的自动旋转?

Ger*_*eri 2 uiviewcontroller uinavigationcontroller uiinterfaceorientation autorotate ios

我还该怎么办?

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation) toInterfaceOrientation
{
    return (toInterfaceOrientation == UIInterfaceOrientationPortrait);
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

-(BOOL)shouldAutoRotate
{
    return NO;
}
Run Code Online (Sandbox Code Playgroud)

我的viewController仍在旋转.


它嵌入在导航堆栈中.如果我将UINavigationController子类化,并在那里实现相同的仅肖像模板,并将我的viewController嵌入到调整后的navigationController中,而不是它的工作原理,但我无意在UINavigationController出现的任何地方重写我的代码.

这里的最佳做法是什么?

Chr*_*oph 6

原始答案:不需要子类 - 只需像我在我的解决方案中描述的那样进行类别: iOS6模拟器中的顶部主页按钮纵向方向不起作用

基本上,对于iPhone,UINavigationController允许旋转除了"顶部主页按钮肖像"之外的所有内容,对于iPad它允许一切.

因此,要么将类别转发给当前活动的视图控制器,要么执行类似静态的操作

UINavigationController的-Rotation.h:

@interface UINavigationController (Rotation)
@end
Run Code Online (Sandbox Code Playgroud)

UINavigationController的-Rotation.m:

#import "UINavigationController-Rotation.h"

@implementation UINavigationController (Rotation)

#pragma From UINavigationController

- (BOOL)shouldAutorotate {

    return NO;
}

- (NSUInteger)supportedInterfaceOrientations {

    return UIInterfaceOrientationMaskPortrait;
}

#pragma -

@end
Run Code Online (Sandbox Code Playgroud)

更新:正如Javier Soto指出的那样,如果第二个类别做同样的事情,这可能会导致未定义的行为.在这种情况下,子类化可能是更好的解决方案.

在您知道没有其他类别做同样事情的情况下,我仍然认为这是一个有效,省力,本地和实用的解决方案.我不是那么虔诚的.决定自己.

  • 添加一个覆盖另一个类的方法的类别会导致未定义的行为,您永远不应该这样做.它现在正常工作的事实是因为iOS在加载类别后最终会使用您的实现,但这可能会改变.此外,如果多个类别覆盖该方法会发生什么?只是子类,这是一个可怕的想法. (2认同)