获取当前界面最上层的TopViewController,目前自己总结了两种方法,一种就是很常规的根据根控制器遍历出导航控制器栈中顶部的控制器找出。最近一直在深入研究runtime,所以就利用runtime中方法交换,把当前最新出现的控制器利用单例存储起来,也能获得到当前控制器。两种方法都可以获取,仁者见仁,智者见智。废话不多少下面上代码。
第一种常规的获取TopViewController:
- (UIViewController *)topViewController {
UIViewController *topVC;
topVC = [self getTopViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
while (topVC.presentedViewController) {
topVC = [self getTopViewController:topVC.presentedViewController];
}
return topVC;
}
- (UIViewController *)getTopViewController:(UIViewController *)vc {
if (![vc isKindOfClass:[UIViewController class]]) {
return nil;
} if ([vc isKindOfClass:[UINavigationController class]]) {
return [self getTopViewController:[(UINavigationController *)vc topViewController]];
} else if ([vc isKindOfClass:[UITabBarController class]]) {
return [self getTopViewController:[(UITabBarController *)vc selectedViewController]];
} else {
return vc;
}
}
第二种利用runtime获取TopViewController:
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Method oldMethod = class_getInstanceMethod([self class], @selector(viewDidAppear:));
Method newMethod = class_getInstanceMethod([self class], @selector(topView_ViewDidAppear:));
// 判断如果这个类没有实现,父类实现了,直接替换父类的方法不是想要的结果
BOOL didChangeMethod = class_addMethod([self class], @selector(viewDidAppear:), method_getImplementation(newMethod), method_getTypeEncoding(newMethod));
if (didChangeMethod) {
class_replaceMethod([self class], @selector(topView_ViewDidAppear:), method_getImplementation(oldMethod), method_getTypeEncoding(oldMethod));
} else {
method_exchangeImplementations(oldMethod, newMethod);
}
});
}
- (void)topView_ViewDidAppear:(BOOL)animated {
[self topView_ViewDidAppear:animated];
if (self.isIgnore == NO) {
[Tool shareCenter].topViewController = self;
NSLog(@"我走了多少次 === %@",[Tool shareCenter].topViewController);
}
}
/**
给分类的属性实现setter方法
@param isIgnore <#isIgnore description#>
*/
-(void)setIsIgnore:(BOOL)isIgnore {
objc_setAssociatedObject(self, &("isIgnore"), @(isIgnore), OBJC_ASSOCIATION_COPY);
}
/**
给分类实现getter方法
@return <#return value description#>
*/
- (BOOL)isIgnore {
id value = objc_getAssociatedObject(self, &("isIgnore"));
return value == nil ? NO : [value boolValue];
}
@end
@implementation Tool
+ (Tool *)shareCenter {
static Tool *tool = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
tool = [[Tool alloc]init];
}); return tool;
}