24.封装MyButton类和Delegate

来源:互联网 发布:中国原油9月进口数据 编辑:程序博客网 时间:2024/06/06 04:42

1.封装一个继承于UIView简单的MyButton类, 模拟实现View的点击事件

MyButton.h和MyButton.m文件

#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.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

MainViewController.m文件

- (void)viewDidLoad {    [super viewDidLoad];    //通过UIView来模拟一个Button的点击    MyButton *myButton = [[MyButton alloc] initWithFrame:CGRectMake(100, 100, 140, 40)];    myButton.backgroundColor = [UIColor yellowColor];    [self.view addSubview:myButton];    [myButton addNewTarget:self Action:@selector(click:)];    [myButton release];}- (void)click:(MyButton *)myButton{    NSLog(@"你好");}

2.Delegate

给继承于UIView的MyButton类添加一个改变颜色的协议方法
MyButton.h和MyButton.m文件

#import <UIKit/UIKit.h>//1.声明一份协议@protocol MyButtonDelegate <NSObject>- (void)changeColor;@end@interface MyButton : UIView//2.设置代理人的属性@property(nonatomic,assign)id<MyButtonDelegate> delegate;@end
#import "MyButton.h"@implementation MyButton//3.设置代理人执行的方法- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{    [self.delegate changeColor];}@end

MainViewController.m文件

#import "MainViewController.h"#import "MyButton.h"//4.签订协议@interface MainViewController ()<MyButtonDelegate>@end@implementation MainViewController- (void)viewDidLoad {    [super viewDidLoad];    MyButton *mybutton = [[MyButton alloc] initWithFrame:CGRectMake(100, 100, 100, 40)];    mybutton.backgroundColor = [UIColor greenColor];    [self.view addSubview:mybutton];    //5.设置代理人    mybutton.delegate = self;    [mybutton release]; }//6.实现代理方法- (void)changeColor{    self.view.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];}
0 0
原创粉丝点击