当界面比较复杂时有时会将一个view单独抽取出来作为一个单独的类.但当涉及到控制器的跳转的时候就不得不用代理或者block回调来去父容器的控制器来进行跳转,很不方便.不过发现一个黑科技如下.
- 创建
TestViewRed
测试view的类
TestViewRed.h
#import <UIKit/UIKit.h>
@interface TestViewRed : UIView
@end
#import "TestViewRed.h"
#import "ViewController.h"
#define KScreen_Bounds [UIScreen mainScreen].bounds
#define KScreen_Size [UIScreen mainScreen].bounds.size
#define KScreen_Width [UIScreen mainScreen].bounds.size.width
#define KScreen_Height [UIScreen mainScreen].bounds.size.height
@interface TestViewRed ()
@property (strong, nonatomic) UIView * view;
@property (strong, nonatomic) UIViewController * vc;
@end
@implementation TestViewRed
-(instancetype)init{
if (self = [super init]) {
self.view = [[UIView alloc] init];
self.view.backgroundColor = [UIColor redColor];
self.view.userInteractionEnabled = YES;
UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickRedView)];
[self.view addGestureRecognizer:tap];
[self addSubview:self.view];
}
return self;
}
//给红色view添加轻触手势
-(void)clickRedView{
UIViewController * vc = [UIViewController new];
ViewController * vcOne = (ViewController *)[self View:self.view];
UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss)];
[vc.view addGestureRecognizer:tap];
self.vc = vc;
vc.view.backgroundColor = [UIColor whiteColor];
[vcOne presentViewController:vc animated:YES completion:nil];
}
//测试弹出的控制器的dismiss方法
-(void)dismiss{
[self.vc dismissViewControllerAnimated:YES completion:^{
}];
}
//重新布局self.view因为如果在init方法中布局self.view则self.frame 都是 0
-(void)layoutSubviews{
self.view.frame = self.frame;
}
//可以获取到父容器的控制器的方法,就是这个黑科技.
- (UIViewController *)View:(UIView *)view{
UIResponder *responder = view;
//循环获取下一个响应者,直到响应者是一个UIViewController类的一个对象为止,然后返回该对象.
while ((responder = [responder nextResponder])) {
if ([responder isKindOfClass:[UIViewController class]]) {
return (UIViewController *)responder;
}
}
return nil;
}
- 在
ViewController
的viewDidLoad
添加如下代码
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
TestViewRed * view = [[TestViewRed alloc] init];
view.frame = CGRectMake(0, 0, KScreen_Width, 360);
view.backgroundColor = [UIColor orangeColor];
[self.view addSubview:view];
}
- 测试效果如下
