只有当vc出现在另一个vc上时,才有支持肖像的类别。要使用它,通常我们使用import UINavigationController + Portrait.h。但是,当我尝试调用另一个vc时,虽然我还没有导入,但supportedInterfaceOrientations始终在我的类别中调用。我可以知道出了什么问题吗?
#import "UINavigationController+Portrait.h"
@implementation UINavigationController (Portrait)
- (BOOL)shouldAutorotate
{
return NO;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationPortrait;
}
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}
//ios4 and ios5
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return NO;
}
答案 0 :(得分:1)
在Objective-C中创建类别时,您定义的任何方法都将影响为该类创建的类的每个实例 - 它不仅会在您导入类别的文件中生效。
Objective-C运行时是动态的,这意味着当您调用方法时,它将在相应的类上查找该方法并调用它。当您通过类别覆盖该方法时,即使不将其导入任何地方,运行时也会寻找正确的方法来调用并发现该类别中定义的方法可用,而是调用它。
这就是UIViewController
的所有实例现在找到您的类别方法的原因。
因此,类别中的重写方法非常危险。相反,正确的做法是子类化一个类并在那里覆盖它的方法。如果这不是一个选项,method swizzling是另一种方式,但它也有自己的风险。