自定义Button点击方法,可实现button回调

2018-02-06  本文已影响129人  碧海云天V
有时候,我们需要在button点击后,取出点击方法执行完后的结果,然而原生的点击方法没有提供回调,那么就需要我们自己进行封装了。下面分两种情况进行了封装,一种是继承,一种是分类。具体看Demo
Jietu20180206-101510.jpg

继承

#import <UIKit/UIKit.h>
@interface BlockButton : UIButton
@property(nonatomic,copy) void(^block)(UIButton*);
-(void)addTapBlock:(void(^)(UIButton *btn))block;
@end


#import "BlockButton.h"
@implementation BlockButton
-(void)addTapBlock:(void(^)(UIButton*))block{
    self.block= block;
    [self addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)click:(UIButton*)btn{
    if(self.block) {
        self.block(btn);
    }
}
@end

调用

#import "BlockButton.h"//引入继承
BlockButton *button0 = [[BlockButton alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
button0.backgroundColor = [UIColor redColor];
[button0 setTitle:@"测试1" forState:0];
[self.view addSubview:button0];
[button0 addTapBlock:^(UIButton *btn) {
     //在这里调用所需要执行的方法
     [self buttonClick];
}];

-(void)buttonClick{
    NSLog(@"点击方法");
}

分类

#import <UIKit/UIKit.h>
@interface UIButton (Block)
@property(nonatomic ,copy)void(^block)(UIButton*);
-(void)addTapBlock:(void(^)(UIButton*btn))block;
@end


#import "UIButton+Block.h"
#import<objc/runtime.h>
@implementation UIButton (Block)
-(void)setBlock:(void(^)(UIButton*))block
{
    objc_setAssociatedObject(self,@selector(block), block,OBJC_ASSOCIATION_COPY_NONATOMIC);
    [self addTarget:self action:@selector(click:)forControlEvents:UIControlEventTouchUpInside];
}
-(void(^)(UIButton*))block
{
    return objc_getAssociatedObject(self,@selector(block));
}
-(void)addTapBlock:(void(^)(UIButton*))block
{
    self.block= block;
    [self addTarget:self action:@selector(click:)forControlEvents:UIControlEventTouchUpInside];
}

-(void)click:(UIButton*)btn
{
    if(self.block) {
        self.block(btn);
    }
}
@end

调用

#import "UIButton+Block.h"//引入分类
UIButton *button1 = [[UIButton alloc] initWithFrame:CGRectMake(100, 300, 100, 100)];
button1.backgroundColor = [UIColor blueColor];
button1.tag = 1001;
[button1 setTitle:@"测试2" forState:0];
[self.view addSubview:button1];
    
__block UIButton *blockSelf = button1;
[button1 addTapBlock:^(UIButton *btn) {
     //在这里调用所需要执行的方法
     [self button:blockSelf callBack:^(NSInteger selectIndex, NSString *title) {
         NSLog(@"tag:%ld    title:%@",(long)selectIndex,title);
     }];
}];

-(void)button:(UIButton *)button callBack:(void (^)(NSInteger selectIndex ,NSString *title))callBack{
    callBack(button.tag,button.currentTitle);
}
这两种方法都可以实现传参和回调,结合具体情况使用吧。
上一篇下一篇

猜你喜欢

热点阅读