標籤:
UIkit架構中絕大多數的控制項都是繼承自,UIResponder類,UIResponder 類有強大的處理觸摸事件的能力。假如一個UIview 收到一個觸摸事件,那麼這個觸摸事件就會去進行尋找相應的響應事件,如果在該UIview 中找不到,就尋找UIView的對象去處理,如果UIView對象沒有權利處理,就往當前的上一層UIViewController去尋找,如果找不到就再尋找 UIViewController 的對象去處理,如果這個對象仍然不能處理,就再往上層 UIWindow 對象去處理,如果它熱不能解決觸摸事件的響應,那該觸摸事件就會被傳遞到 UIApplication 代理對象,如果該代理對象仍不能解決,那就交給系統回收。
總結一下:相當於在村裡發生一件事,村長不能決定,這時就一級一級上報,可是一直沒有得到處理,直到最後有個很大權力的人拍板決定,才算結束。要不就一直往上報。
系統將事件封裝到 UIEvent 類中,然後由系統去處理。ios 將事件分為三種:觸摸事件、動作事件、外部控制事件。動作事件:就是使用者對手機進行的特定的動做,比如搖一搖;外部控制事件:就是控制手機連上手機裝置時候的事件;觸摸事件:就是使用者與手機螢幕的相關事件。
每一個使用者互動對象 UIResponder 都有一組響應事件函數。通常我們都要重寫這組函數。以供我們使用相應的邏輯。
關於概念的知識這裡就不再多說看部落格網址(http://blog.csdn.net/yitailong/article/details/8228946)
基本代碼實現:列印出滑鼠的手勢事件
建一個 UIView 的檔案命名為 TouchView 在視圖控制器裡寫上
#import "RootViewController.h"#import "TouchView.h"@interface RootViewController ()@end@implementation RootViewController- (void)viewDidLoad { [super viewDidLoad]; [self setTouchView];}-(void)setTouchView{ TouchView * touchView = [[TouchView alloc]initWithFrame:CGRectMake(50, 50, 100, 100)]; touchView.backgroundColor = [UIColor redColor]; [self.view addSubview:touchView]; UIButton * Button = [UIButton buttonWithType:UIButtonTypeCustom]; Button.frame = CGRectMake(20, 200, 280, 30); Button.backgroundColor = [UIColor grayColor]; [Button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside]; [Button setTitle:@"點擊跳轉" forState:UIControlStateNormal]; [self.view addSubview:Button]; pinchView * View = [[pinchView alloc]initWithFrame:CGRectMake(50, 300, 100, 100)]; View.backgroundColor = [UIColor blackColor]; [self.view addSubview:View]; }-(void)buttonAction:(UIButton *)sender{ SecondViewController * SVC = [[SecondViewController alloc]init]; [self.navigationController pushViewController:SVC animated:YES];}- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}View Code
在 UIView.m檔案裡寫上
#import "TouchView.h"@implementation TouchView-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ [self updateInfor:[touches anyObject] withMethodName:@"touchesBegin"];}-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{ [self updateInfor:[touches anyObject] withMethodName:@"touchesCancelled"];}-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ [self updateInfor:[touches anyObject] withMethodName:@"touchesEnded"];}-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ [self updateInfor:[touches anyObject] withMethodName:@"touchesMoved"];}-(void)updateInfor:(UITouch *)aTouch withMethodName:(NSString *)aMethodName{ NSString * strPhase = @""; switch (aTouch.phase) { case UITouchPhaseBegan: strPhase = @"UITouchPhaseBegan"; break; case UITouchPhaseEnded: strPhase = @"UITouchPhaseEnded"; break; case UITouchPhaseCancelled: strPhase = @"UITouchPhaseCancelled"; break; case UITouchPhaseMoved: strPhase = @"UITouchPhaseMoved"; break; default: break; } NSLog(@"操作事件是 %@",strPhase);}@endView Code
2015-10-31 iOS 中的手勢