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

UI_Target-Action

2015-08-12 20:23 483 查看
通过UIView来模拟一个button的点击

#import <UIKit/UIKit.h>

@interface MyButton : UIView

// 通过MyButton实现button的点击效果
// 1.通过自定义的方法,把目标和动作传到类的内部
- (void)addNewTarget:(id)target Action:(SEL)action;
// target目标,button执行哪一个类的方法,对应的目标就是那个类的对象
// 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.target = target;
self.action = action;
}

// 4.给Button一个触发的条件, 重写触摸开始方法,只要一触碰视图,就调用touchesBegan方法,让button执行相应的点击方法
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// 5.类把它的方法,交给MyButton来完成
[self.target performSelector:self.action withObject:self];
}

@end


#import "MainViewController.h"
#import "MyButton.h"
#import "TestButton.h"
@interface MainViewController ()

@end

@implementation MainViewController

- (void)viewDidLoad {
[super viewDidLoad];

// 通过UIView来模拟一个button的点击
MyButton *mybutton = [[MyButton alloc] initWithFrame:CGRectMake(120, 100, 150, 40)];
mybutton.backgroundColor = [UIColor magentaColor];
[self.view addSubview:mybutton];
[mybutton release];

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

TestButton *testButton = [[TestButton alloc] initWithFrame:CGRectMake(120, 200, 150, 40)];
testButton.backgroundColor = [UIColor cyanColor];
[self.view addSubview:testButton];
[testButton release];

[testButton addNewTarget:self Action:@selector(click2:)];
}

- (void)click1:(MyButton *)button
{
NSLog(@"实现点击效果");
}

- (void)click2:(TestButton *)button
{
NSLog(@"测试成功");
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: