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
相关文章推荐
- UITouch 摇晃手势启动器
- UIViewController
- HDU 5146 Sequence 回文数组
- poj2442---Sequence
- PDO对象之query()方法
- UIViewController
- 【Baltic2007】【BZOJ1345】序列问题Sequence
- Leetcode62 Unique Paths
- UITabBar
- uva uva 1605 - Building for UN
- POJ 2031 Building a Space Station(最小生成树--prime)
- poj 1679 The Unique MST【次小生成树】
- Uniqueidentifier数据类型
- 黑马程序员——java学习13(毕22)——GUI
- Implement Queue using Stacks
- UINavigationController的代理方法
- UITabBar,快捷菜单,block实现传值
- 读书笔记-APUE第三版-(10)信号
- Modeling with Sequence Diagram
- 自定义UITableViewCell(2) 多个自定义cell