1.通过对按钮的封装,从而减少了代码量,我们不需要大段落的去创建按钮,只要通过封装的Button类创建即可,这里我们利用block来进行封装.
(1)首先创建一个类,继承Button类
(2)然后定义block
(3)定义类方法
(4)在.m中实现类方法
2.具体代码如下:
(1)在.h文件中
#import <UIKit/UIKit.h>
@class MGButton;
typedef void (^block)(MGButton *button);
@interface MGButton : UIButton
+ (MGButton *)buttonWithFrame:(CGRect)frame type:(UIButtonType)type title:(NSString *)title addBlock:(block)tempBlock;
@end
(2)在.m文件中实现类方法
#import "MGButton.h"
@interface MGButton()
//注意:给block变量写合成存取,一定要使用copy
@property (nonatomic,copy) block myBlock;
@end
@implementation MGButton
//利用block生成button对象
+ (MGButton *)buttonWithFrame:(CGRect)frame type:(UIButtonType)type title:(NSString *)title addBlock:(block)tempBlock {
MGButton *button = [MGButton buttonWithType:type];
[button setTitle:title forState:UIControlStateNormal];
button.frame = frame;
[button addTarget:button action:@selector(buttonCilcked:) forControlEvents:UIControlEventTouchUpInside];
button.myBlock = tempBlock;
return button;
}
//按钮的点击事件
- (void)buttonCilcked:(MGButton *)button {
// NSLog(@"这里是buttonCilcked方法的内部");
//触发按钮
button.tag = 10;
button.myBlock(button);
}
@end
3.创建按钮,可以引入MGButton的头文件,通过类方法创建按钮即可
代码如下:
UIButton *btn = [MGButton buttonWithFrame:CGRectMake(0, 0, 200, 44) type:UIButtonTypeCustom title:@"按钮" addBlock:^(MGButton *button) {
NSLog(@"按钮点击事件");
}];
[self.view addSubview:btn];
4.其他形式的按钮,可以根据自己项目中的需要,自定义block方法的实现。