IOS开发 事件响应链

本节学习内容:

1.事件响应链的概念

2.事件响应链的传递机制

3.事件响应链的应用


IOS开发 事件响应链_第1张图片
事件响应原理

响应顺序 Subview>MainView>UIView>VCRoot>MyWindow>UIApplication>AppDelegate

1.添加一个视图控制器命名为VCRoot

【VCRoot.h】

#import

#import"MainView.h"

#import"subView.h"

@interface VCRoot:UIViewConroller{

//主视图定义

MainView * _mainView

//子视图对象定义

SubView* _subView;

}

@end

【VCRoot.m】

#import"VCRoot.h"

@interface VCRoot()

@end

@implementation VCRoot

-(void)viewDidLoad{

[super viewDidLoad];

//创建主视图

_mainView=[[MainView alloc]init];

_mainView.frame=CGRectMAke(50,50,200,300);

_mainView.backgroundColor=[UIColor orangeColor];

[self.view addSubview:_mainView];

//创建子视图

_subView=[[subView alloc]init];

_subView.frame=CGRectMake(30,30,100,200);

[_mainView addSubview:_subView];

[self.view addSubview:_mainView];

//改变视图背景颜色

self.view.backgroundColor=[UIColor blueColor];

}

//当点击屏幕时,调用此函数

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{

NSLog(@"RootView 事件响应!");

}

2.创建一个主视图命名为:mainview

#import"MainView.h"

@iplementation MainView

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{

NSLog(@"MainView 事件响应!next==@%",self.nextResponder);

//手动响应下传递

[super touchesBegan:touches withEvent:event];

}

3.创建一子视图命名为SubView

【SubView.m】

#import"subView.h"

@implementation subView

//在子视图中优先级最高,当响应事件,事件到此结束-

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{

NSLog(@"SubView 事件响应!next==@%",self.nextResponder);

//手动响应下传递

[super touchesBegan:touches withEvent:event];

}

4.创建一个Window命名为MyWindow

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{

NSLog(@"MyWindow事件响应!next==@%",self.nextResponder);

//手动响应下传递

[super touchesBegan:touches withEvent:event];

}

5.创建一个UIApplication命名为MyApplication

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{

NSLog(@"MyApplication 事件响应!next==@%",self.nextResponder);

//手动响应下传递

[super touchesBegan:touches withEvent:event];

}


【AppDelegate.m】

#import"AppDelegate.h"

#import"VCRoot.h"

#import"Myapplication.h"

#import"MyWindow.h"

@interface AppDelegate()

@end

@implementation AppDelegate

//appdelegate是最后一个响应

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{

NSLog(@"MyApplication 事件响应!next==@%",self.nextResponder);

//手动响应下传递

[super touchesBegan:touches withEvent:event];

}

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

//创建一个window对象

self.window=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];

//根视图控制器创建

self.window.rootViewController=[[VCRoog alloc]init];

[self.window makeKeyAndVisible];

return YES;

}

执行结果事件响应顺序:

IOS开发 事件响应链_第2张图片
事件响应顺序日志






你可能感兴趣的:(IOS开发 事件响应链)