您的位置:首页 > 产品设计 > UI/UE

UIResponder - 3

2016-01-08 17:49 567 查看
如果想通过视图获取自身,或者是superView的视图控制器类,想起来觉得非常不可以思议,但是通过UIResponder的响应链就非常好实现,我们可以重新看回UIResponder - 1 文章,有一张响应者链的图:



通过这个,就非常好实现了,参考:
http://apluck.iteye.com/blog/1748432
- (UIViewController*)viewController
{
for (UIView* next = [self superview]; next; next = next.superview)
{
UIResponder* nextResponder = [next nextResponder];

if ([nextResponder isKindOfClass:[UIViewController class]])
{
return (UIViewController*)nextResponder;
}
}

return nil;
}

测试:
1.直接添加子类:

#import "LBAccessViewController.h"

@interface LBAccessViewController ()

@end

@implementation LBAccessViewController

- (void)viewDidLoad
{
[super viewDidLoad];

LBAccessView* myview = [[LBAccessView alloc] init];
[self.view addSubview:myview];

NSLog(@"self : %@", self);
NSLog(@"access : %@", [myview viewController]);
}

@end

#pragma mark - LBAccessView.

@implementation LBAccessView

- (UIViewController*)viewController
{
for (UIView* next = [self superview]; next; next = next.superview)
{
UIResponder* nextResponder = [next nextResponder];

if ([nextResponder isKindOfClass:[UIViewController class]])
{
return (UIViewController*)nextResponder;
}
}

return nil;
}

@end

输出:



2.先添加其他视图,即嵌套一层视图:

UIView* containView = [[UIView alloc] init];
[self.view addSubview:containView];

LBAccessView* myview = [[LBAccessView alloc] init];
[containView addSubview:myview];

NSLog(@"self : %@", self);
NSLog(@"access : %@", [myview viewController]);

输出依旧

当然还有别的方法:

如果存在导航栏NavigationController可以使用这个方法:

@property(nullable, nonatomic,readonly,strong) UIViewController *visibleViewController; // Return modal view controller if it exists. Otherwise the top view controller.


拿到当前看得到的视图控制器,如果木有的话,返回最顶层的视图控制器。

参考:

Reference - 1 : http://apluck.iteye.com/blog/1748432

Reference - 2 : http://www.cnblogs.com/maxfong/p/3423633.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  iOS UIResponder