UI笔记_target...action设计模式

来源:互联网 发布:c语言ld return 1exit 编辑:程序博客网 时间:2024/05/29 16:32

耦合

耦合是衡量模块与模块之间关联程度的指标。

耦合是衡量一个程序写的好坏的标准之一。

“高内聚,低耦合”是面向对象编程的核心思想。

关于耦合和聚合的更多内容请戳:面向对象编程中的聚合与耦合

target...action设计模式

target...action和delegate设计模式都是用来解耦合的。

target...action解耦合方法:

1.创建一个UIView的子类(eg: UIButtonView)

2.添加两个属性,id target 要执行方法的对象,SEL action 要执行的方法

3.添加一个addTarget:action: 方法,内部实现: self.target = target; self.action = action;

4.在touchesEnded:withEvents: 方法中添加,[self.target = performSelector:self.action];

5.在视图控制器中导入自定义的视图

6.创建自定义视图,并调用addTarget:action: 方法,将视图添加到self.view上

7.实现给定的selector方法

target...action的使用场景:需要让一个目标去执行一个动作的地方

对比delegate设计模式

使用delegate解耦合方法:

1.创建一个UIView子类xxxView

2.在.h文件中创建一个xxxViewDelegate协议,里面包含3个optional方法viewTouchBegan:;viewTouchMoved:;viewTouchEnded: 

3.给xxxView添加一个属性id <xxxViewDelegate> delegate

4.xxxView.m的touchesBegan: withEvent:方法中写如下代码if([_delegate respondToSelector: @selector(viewTouchBegan:)]){[_delegate viewTouchBegan:self]},其他触摸事件的实现同上 

5.viewController.m文件import 自定义的视图

6.创建自定义视图,指定xxView的delegate,将视图添加到self.view上

7.实现xxxViewDelegate中的方法

delegate的使用场景:让一个对象去监控自定义控件的状态



0 0
原创粉丝点击