解释为什么imgView要打开点击事件事件响应链
Posted pengyuan_D
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了解释为什么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要打开点击事件事件响应链的主要内容,如果未能解决你的问题,请参考以下文章
1% 的时间没有处理 UIButton 事件:我应该在我的响应链中责备谁?