首页 > 代码库 > 解释为什么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要打开点击事件【事件响应链】
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。