UI 04 target...action 设计模式
2015-08-04 22:02
330 查看
“高内聚,低耦合”是面向对象编程的核心思想.
使用 target…action 实现解耦.
需要目标去执行一个动作的地方.
例如, 定义一个继承于UIView 的MyButton 类, 让他能够有Button的点击方法.
代码如下:
Mybutton.h:
Mybutton.m:
回到根视图的.m文件,代码如下:
使用 target…action 实现解耦.
需要目标去执行一个动作的地方.
例如, 定义一个继承于UIView 的MyButton 类, 让他能够有Button的点击方法.
代码如下:
Mybutton.h:
#import <UIKit/UIKit.h> @interface Mybutton : UIView //1.写一个自定义方法,把目标和对应动作传过来. - (void)addNewTarget:(id)target Action:(SEL)action; //2.定义两条属性. @property(nonatomic, assign)id target; @property(nonatomic, assign)SEL action; @end
Mybutton.m:
#import "Mybutton.h" @implementation Mybutton - (void)addNewTarget:(id)target Action:(SEL)action{ // 目标动作保存到属性中. self.target = target; self.action = action; } //4.给他一个触发的条件. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ [self.target performSelector:self.action withObject:self]; } @end
回到根视图的.m文件,代码如下:
#import "MainViewController.h" #import "Mybutton.h" @interface MainViewController () @end @implementation MainViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. // 通过UIView来模拟一个Button的点击事件. Mybutton *View_button = [[Mybutton alloc] initWithFrame:CGRectMake(100, 100, 150, 100)]; View_button.backgroundColor = [UIColor orangeColor]; [self.view addSubview:View_button]; [View_button release]; //6.使用自定义方法 [View_button addNewTarget:self Action:@selector(click:)]; } - (void)click:(Mybutton *)button{ // 检测是否成功. NSLog(@"成功!"); }
相关文章推荐
- iOS开发——UI进阶篇(十六)Quartz2D实战小例子
- HDU1.2.6 Buildings
- UVA1152 4Values whose Sum is 0
- HDU 5301 Buildings
- DPDK 的 uio 以及 PMD 机制的实现
- minicom question
- 记录一下iOS的几个UIView的方法
- UI 03 自定义的Label-TextField视图 --- LTView
- iOS开发——UI进阶篇(十五)Quartz2D介绍
- UISwitch设置代理人 帮助实现变换背景颜色
- ios学习(UITabBarController)
- poj 2299 Ultra-QuickSort (树状数组+离散化)
- HD1047 Integer Inquiry 【大数问题】
- iOS UI04_Target-Action
- BIM建筑信息模型(Building Information Modeling)
- UI 03 UIViewController (视图控制器)的7个方法与视图的跳转
- Disque: antirez开发的开源分布式内存作业队列
- UI Overview
- 27.UIStepper和UISlider
- 通过UIView来模拟 实现 Button的点击效果