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
- 24.封装MyButton类和Delegate
- Func<> Delegate和Action<> Delegate
- 自定义组件—MyButton
- Delegate类
- Delegate 类
- [C#-2] delegate和Delegate的区别
- 说说Delegate和Event
- delegate和protocol
- protocol和delegate
- [iOS]delegate和protocol
- [iOS]delegate和protocol
- [iOS]delegate和protocol
- delegate和protocol
- delegate和protocol
- delegate和protocol
- [iOS]delegate和protocol
- protocol和delegate
- delegate和protocol(区别)
- J114 8/2
- SQL 常用语句
- Apache服务器配置多个虚拟主机
- HDU 1112 The Proper Key DFS+模拟
- 我为什么反对提“全栈工程师”?
- 24.封装MyButton类和Delegate
- 关于android:showAsAction
- list排序
- Linux tr 命令
- wget命令详解,断点续传
- IOS绘图API绘制直线几何图形
- 第二周周一
- UI 03 UIButton 和 UITextField
- HDOJ 5338 ZZX and Permutations 线段树+树状数组