首页 > 代码库 > 解释为什么imgView要打开点击事件【事件响应链】

解释为什么imgView要打开点击事件【事件响应链】

(1)在AppDelegate.m文件中将导航控制器设置为根控制器

RootViewController *rootCtrl = [[RootViewController alloc] init];
    UINavigationController *navCtrl = [[UINavigationController  alloc] initWithRootViewController:rootCtrl];
    
    self.window.rootViewController = navCtrl;

(2)添加MyView到RootViewController,并设置背景颜色

(3)给UIView添加一个类目

UIView+ViewController.h

//获取当前试图所在的视图控制器
- (UIViewController *)viewController;
UIView+ViewController.m

- (UIViewController *)viewController
{

    UIResponder *next = self.nextResponder;
    do
    {
        if ([next isKindOfClass:[UIViewController class]])
        {
            return (UIViewController *)next;
        }
        next = next.nextResponder;
    }while (next != nil);
    
    return nil;
}



(4)创建MyView视图,继承与UIView

MyView.m

#import "MyView.h"
#import "SecondViewController.h"
#import "UIView+ViewController.h"

@implementation MyView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self _initButton];
    }
    return self;
}

- (void)_initButton
{

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(100, 100, 90, 90);
    button.backgroundColor = [UIColor greenColor];
    [button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:button];
    
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 40, 90, 50)];
    imgView.backgroundColor = [UIColor grayColor];
    //注意:当imgView添加在button上面作为子视图的时候,不能响应事件,否则按钮不能接收到事件
//    imgView.userInteractionEnabled = YES;
    [button addSubview:imgView];
    
}

- (void)buttonAction {

    SecondViewController *secondCtrl = [[SecondViewController alloc] init];
    
    //取得当前视图所在的视图控制器
    UIViewController *viewCtrl = [self viewController];
    
    if (viewCtrl != nil) {
        [viewCtrl.navigationController pushViewController:secondCtrl animated:YES];
    }
    
}

@end
(5)创建SecondViewController,并设置背景颜色



解释为什么imgView要打开点击事件【事件响应链】