UI -响应者链

什么是响应者?
UIResponder。响应者类。
iOS中所有能响应事件(触摸、晃动、远程事件)的对象都是响应者。
系统定义了⼀一个抽象的⽗父类UIResponder来表⽰示响应者。其⼦子类都是响应者。

检测触碰视图
硬件检测到触摸操作,会将信息交给UIApplication,开始检测。
UIApplication -> window -> viewController -> view -> 检测所有⼦子 视图
最终确认触碰位置,完成响应者链的查询过程。

UIApplication->window- >rootViewController
viewA -> ViewB
viewC -> ViewD -> ViewE(检测到触 摸视图)
如图1-1所示:
图1-1

处理触碰事件
检测到响应者后,实现touchesBegan:withEvent:等⽅方法,即处理事 件。
如果响应者没有处理事件,事件会向下传递。如果没有响应者处理,
则丢弃触摸事件。
事件处理的顺序与触摸检测查询相反。
触摸的⼦子视图 -> view -> viewController -> window -> UIApplication

查询与处理可能会出现在面试题中.

阻断响应者链:
响应者链可以被打断。⽆无法完成检测查询过程。
视图类的属性 : userInteractionEnabled。关闭后能阻断查询过 程。

代码展示

#ResponderView.h

#import <UIKit/UIKit.h>

@interface ResponderView : UIView
@property(nonatomic,retain,readonly)UILabel *label;
@property(nonatomic,retain,readonly)UIButton *button;
@end

#ResponderView.m

#import "ResponderView.h"

@implementation ResponderView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (void)dealloc
{
    [_label release];
    [super dealloc];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _label = [[UILabel alloc]initWithFrame:CGRectMake(30, 30, 200, 100)];
        [self addSubview:_label];
        _button = [UIButton buttonWithType:(UIButtonTypeSystem)];
        _button.frame = CGRectMake(10, 10, 100, 30);
        [_label addSubview:_button];
    }
    return self;
}
@end

#ResponderViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 在label上创建一个button,在button添加事件
    ResponderView *responderView = [[ResponderView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.view = responderView;

    responderView.label.text = @"哈哈";
    responderView.label.backgroundColor = [UIColor lightGrayColor]; // xcode8的一个bug
    // 在UI中,基本上所有的控件的用户交互都是打开的 但是也有一些特例 例如label,imageView
    // userInteractionEnabled这个属性影响了响应者链的检测过程 所以如果将一个button放在一个label或者是imageView上 都需要将;label或者是imageView的用户交互打开才可以 否则在检测的过程中是检测不到label或者imageView上的子视图的
    responderView.label.userInteractionEnabled = YES;
    [responderView.button setTitle:@"点击" forState:(UIControlStateNormal)];
    responderView.button.backgroundColor = [UIColor whiteColor];
    [responderView.button addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
    // label的userInteractionEnabled默认是关闭的(用户交互)  

    [responderView release];
}

- (void)click
{
    NSLog(@"哈哈");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值