UIButton的点击事件写成Block,AlertView的delegate写成Block


每次使用UIButton的点击事件都要新写一个方法,感觉太麻烦,今天下来无事就用block封装了一下button的操作事件,这样以后能省下一些时间,而且代码量也减少了不少。

下面我写上源码:

我写的是UIButton的类目

h文件:

#import <UIKit/UIKit.h>
typedef void (^ActionBlock)();
typedef void (^Block_SureEvent)();
@interface UIButton (Block)<UIAlertViewDelegate>
-(void)handleClickEvent:(UIControlEvents)aEvent withClickBlick:(ActionBlock)buttonClickEvent;
-(void)AlertViewTitle:(NSString *)aTitle message:(NSString *)aMsg cancleButtonTitle:(NSString *)aButtonTitle sureButtonTitle:(NSString *)aSureButton sureBlockEvent:(Block_SureEvent)aSureEvent;
@end

 下面是m文件

#import "UIButton+Block.h"

#import <objc/runtime.h>

static char *overViewKey;
@implementation UIButton (Block)
-(void)handleClickEvent:(UIControlEvents)aEvent withClickBlick:(ActionBlock)buttonClickEvent
{
    objc_setAssociatedObject(self, &overViewKey, buttonClickEvent, OBJC_ASSOCIATION_COPY_NONATOMIC);
    [self addTarget:self action:@selector(buttonClick) forControlEvents:aEvent];
}
-(void)buttonClick
{
    ActionBlock blockClick = objc_getAssociatedObject(self, &overViewKey);
    if (blockClick != nil)
    {
        blockClick();
    }
}
@end
其中要想使用关联对象的objc_setAssociatedObject和objc_getAssociatedObject必须引用头文件objc/runtime.h

objc_setAssociatedObject的四个参数分别为:源对象,key[必须是 static char类型],关联对象,关联方式【与修饰属性类似】

objc_getAssociatedObject的两个参数:源对象,key。通过这两个参数可以获取关联的对象。

--------------------------------AlertView----------------------Block-----------------------------------------

static char * alertKey;

-(void)AlertViewTitle:(NSString *)aTitle message:(NSString *)aMsg cancleButtonTitle:(NSString *)aButtonTitle sureButtonTitle:(NSString *)aSureButton sureBlockEvent:(Block_SureEvent)aSureEvent

{

    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:aTitle message:aMsg delegate:self cancelButtonTitle:aButtonTitle otherButtonTitles:aSureButton, nil];
    objc_setAssociatedObject(self, &alertKey, aSureEvent, OBJC_ASSOCIATION_COPY_NONATOMIC);
    [alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        
        Block_SureEvent blockSure = objc_getAssociatedObject(self, &alertKey);
        if (blockSure != nil)
        {
            blockSure();
        }
        else
        {
            NSLog(@"error");
        } 
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值