您的位置:首页 > 产品设计 > UI/UE

UI_Target-Action

2015-08-03 09:22 387 查看
Target-Aciton:

目标-动作模式

// 建一个UIView类型的MyButton ,实现UIButton的点击功能

先建立一个继承于UIView的类, MyButton

#import <UIKit/UIKit.h>
@interface Mybutton : UIView

//  1.通过自定义的方法,把目标和动作传到类的内部
- (void)addNewTarget:(id)target
Action:(SEL)action;
target:目标, buttton执行哪个类的方法,对应的目标就是哪个类的对象
action:动作, 让button具体做什么事情,执行的方法就是对应的动作

//  2.通过两条属性,把对应的目标和动作保存起来
@property(nonatomic, assign)id  target;
@property(nonatomic, assign)SEL action;

@end

#import "Mybutton.h"
@implementation Mybutton
- (void)addNewTarget:(id)target Action:(SEL)action{
// 3.实现对应的自定义方法,并让两个属性来保存
self.action = action;
self.target =target;
}

// 4.给Button一个触发的条件,重写触发的方法,只要以碰触touchesBegan方法,就会让Button执行相应的点击方法
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

// 5.类把它的方法, 交给MyButton来完成
[self.target performSelector:self.action withObject:self];
}

@end


// 通过UIView来模拟一个button的点击

#import "MainViewController.h"
#import "Mybutton.h"
@interface MainViewController ()
@end

@implementation MainViewController

- (void)viewDidLoad {
[super viewDidLoad];

Mybutton *myButton = [[Mybutton alloc]initWithFrame:CGRectMake(100, 100, 150, 40)];
myButton.backgroundColor = [UIColor orangeColor];
[self.view addSubview:myButton];
[myButton release];

// 6.使用自定义的初始化方法
[myButton addNewTarget:self Action:@selector(click:)];

}

- (void)click:(Mybutton *)button{
NSLog(@"实现点击效果");
}
.....
@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: