Target/Action 設計模式介紹
Target/Action 設計模式可以實現高內聚低耦合的特點, 可以實現解耦
在一般的視圖類中, 如果直接使用觸摸事件的響應方法的話, 不夠靈活, 對於不同的視圖,在相同的觸摸事件中如果要實現不同的功能, 那麼每次使用觸摸事件時, 都需要修改代碼, 非常麻煩.
我們可以通過 Target/Action 設計模式, 讓我們的 View類 像 Button 一樣靈活(Button 的響應方法就是 target/action 設計模式)
//添加 Button 的響應事件
[button addTarget:self action:@selector(handleButtonAction:) forControlEvents:UIControlEventTouchUpInside];
Target/Action 設計模式的使用步驟
1 . 在我們的 View 類中的.h文件定義一個給外界提供的接口, 用於獲取觸摸響應的目標(target), 以及響應觸摸事件之後需要實現的方法(action)
- (void)addTarget:(id)target Action:(SEL)action;
2 . 在我們的 View 類的延展中定義兩個實例變量
{
//此處只做簡單地存儲, 不牽扯到 alloc, 及內存管理問題, 可以直接使用
id _target;//存儲響應的目標
SEL _action;//存儲響應的方法
}
3 . 在 View 的.m文件中實現 addTarget: Action: 方法
- (void)addTarget:(id)target Action:(SEL)action {
//存儲外界的響應目標和方法
_target = target;
_action = action;
}
4 . 在觸摸事件的方法中, 實現當 view 接到觸摸事件時, 通知 target 執行 action 的功能.
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// 當 View 接到觸摸事件時, 通知 target 執行 action 方法
[_target performSelector:_action withObject:self];
}
5 . 在視圖控制器中調用 addTarget: Action: 方法
ActionView *redView = [[ActionView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
redView.tag = 200;
redView.backgroundColor = [UIColor redColor];
[redView addTarget:self Action:@selector(changeSelfColor:)];
[self.view addSubview:redView];
[redView release];