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];
}
  • 測試效果如下


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM