本節(jié)學(xué)習內(nèi)容:
1.事件響應(yīng)鏈的概念
2.事件響應(yīng)鏈的傳遞機制
3.事件響應(yīng)鏈的應(yīng)用
響應(yīng)順序 Subview>MainView>UIView>VCRoot>MyWindow>UIApplication>AppDelegate
1.添加一個視圖控制器命名為VCRoot
【VCRoot.h】
#import<UIKit/UIKit>
#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];
//創(chuàng)建主視圖
_mainView=[[MainView alloc]init];
_mainView.frame=CGRectMAke(50,50,200,300);
_mainView.backgroundColor=[UIColor orangeColor];
[self.view addSubview:_mainView];
//創(chuàng)建子視圖
_subView=[[subView alloc]init];
_subView.frame=CGRectMake(30,30,100,200);
[_mainView addSubview:_subView];
[self.view addSubview:_mainView];
//改變視圖背景顏色
self.view.backgroundColor=[UIColor blueColor];
}
//當點擊屏幕時供屉,調(diào)用此函數(shù)
-(void)touchesBegan:(NSSet<UITouch*>*)touches withEvent:(UIEvent *)event{
NSLog(@"RootView 事件響應(yīng)!");
}
2.創(chuàng)建一個主視圖命名為:mainview
#import"MainView.h"
@iplementation MainView
-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{
NSLog(@"MainView 事件響應(yīng)溺蕉!next==@%",self.nextResponder);
//手動響應(yīng)下傳遞
[super touchesBegan:touches withEvent:event];
}
3.創(chuàng)建一子視圖命名為SubView
【SubView.m】
#import"subView.h"
@implementation subView
//在子視圖中優(yōu)先級最高,當響應(yīng)事件伶丐,事件到此結(jié)束-
-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{
NSLog(@"SubView 事件響應(yīng)!next==@%",self.nextResponder);
//手動響應(yīng)下傳遞
[super touchesBegan:touches withEvent:event];
}
4.創(chuàng)建一個Window命名為MyWindow
-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{
NSLog(@"MyWindow事件響應(yīng)疯特!next==@%",self.nextResponder);
//手動響應(yīng)下傳遞
[super touchesBegan:touches withEvent:event];
}
5.創(chuàng)建一個UIApplication命名為MyApplication
-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{
NSLog(@"MyApplication 事件響應(yīng)哗魂!next==@%",self.nextResponder);
//手動響應(yīng)下傳遞
[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是最后一個響應(yīng)
-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{
NSLog(@"MyApplication 事件響應(yīng)!next==@%",self.nextResponder);
//手動響應(yīng)下傳遞
[super touchesBegan:touches withEvent:event];
}
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
//創(chuàng)建一個window對象
self.window=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
//根視圖控制器創(chuàng)建
self.window.rootViewController=[[VCRoog alloc]init];
[self.window makeKeyAndVisible];
return YES;
}
執(zhí)行結(jié)果事件響應(yīng)順序: