首页 > 其他 > 详细

UI 04 target...action 设计模式

时间:2015-08-04 22:54:03      阅读:214      评论:0      收藏:0      [点我收藏+]

“高内聚,低耦合”是面向对象编程的核心思想.
使用 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(@"成功!");
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

UI 04 target...action 设计模式

原文:http://blog.csdn.net/gao_zi/article/details/47283583

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!