iOS - 从view中获取控制器

当界面比较复杂时有时会将一个view单独抽取出来做为一个单独的类.但当涉及到控制器的跳转的时候就不得不用代理或者block回调来去父容器的控制器来进行跳转,很不方便.不过发现一个黑科技以下.

  • 建立TestViewRed测试view的类
  • TestViewRed.h
#import <UIKit/UIKit.h>

@interface TestViewRed : UIView

@end
  • TestViewRed.m
#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;
}
  • ViewControllerviewDidLoad添加以下代码
- (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];
}
  • 测试效果以下
相关文章
相关标签/搜索