IOS開發 事件響應鏈

本節學習內容:

1.事件響應鏈的概念

2.事件響應鏈的傳遞機制

3.事件響應鏈的應用


事件響應原理

響應順序 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];

//創建主視圖

_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<UITouch*>*)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;

}

執行結果事件響應順序:

事件響應順序日志






最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容