不使用RAC如何回调类方法里的block?

无敌鲨鱼炮
  • 448
+ (void)showAlertWithType:(NSInteger)type buttonClickedBlock:(void (^)(void))buttonClickedBlock {
    
    UIWindow *delegateWindow = [[[UIApplication sharedApplication] delegate] window];
    
    // 灰色view
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(90, 90, 200, 200)];
    [delegateWindow addSubview:bgView];
    bgView.backgroundColor = [UIColor grayColor];
    
    // 按钮(点击按钮让灰色view变成红色)
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [bgView addSubview:button];
    button.frame = CGRectMake(30, 30, 90, 40);
    [button setTitle:@"点击变红" forState:UIControlStateNormal];
    
    // 怎么实现点击按钮让灰色view变红并且执行block?(不使用RAC)
    //button addTarget:<#(nullable id)#> action:<#(nonnull SEL)#> forControlEvents:<#(UIControlEvents)#>
}

这个类方法是弹出一个灰色view,灰色view上有一个按钮,现在我想点击这个按钮后让灰色view的颜色变成红色并且回调block。

问:如果不用RAC,你们会怎么实现?

回复
阅读 1.6k
2 个回答
✓ 已被采纳

打算自定义就继承UIView,比如写一个 MyAlertView 继承自 UIView,该类有一个 + (void)showAlertWithType:(NSInteger)type buttonClickedBlock:(void (^)(void))buttonClickedBlock 方法,有一个button属性,然后 MyAlertView 持有该block,在button点击的时候执行该block。
如果你不想新建一个类,那就用分类给button添加一个属性,保存block,点击的时候再执行。

何锦涛
  • 5
新手上路,请多包涵

我是这么做的 亲测可用 你可以试试

//UIButton+HJTBlock.h
-(void)hjt_addEventHandler:(void (^) (UIButton *sender)) block forUIControlEvents:(UIControlEvents)controlEvents;
//UIButton+HJTBlock.m
#import "UIButton+HJTBlock.h"
#import <objc/runtime.h>

typedef void(^HJT_ButtonEventsBlock)(UIButton *sender);

@interface UIButton ()

//event callback
@property (nonatomic,copy) HJT_ButtonEventsBlock hjt_buttonEventBlock;

@end

@implementation UIButton (HJTBlock)

static void *hjt_buttonEventsBlockKey = &hjt_buttonEventsBlockKey;

-(HJT_ButtonEventsBlock)hjt_buttonEventBlock{
    return objc_getAssociatedObject(self,&hjt_buttonEventsBlockKey);
}

-(void)setHjt_buttonEventBlock:(HJT_ButtonEventsBlock)hjt_buttonEventBlock{
    objc_setAssociatedObject(self, &hjt_buttonEventsBlockKey,hjt_buttonEventBlock,OBJC_ASSOCIATION_COPY);
}

-(void)hjt_addEventHandler:(void (^)(UIButton *))block forUIControlEvents:(UIControlEvents)controlEvents{
    self.hjt_buttonEventBlock = block;
    [self addTarget:self action:@selector(hjt_buttonClick) forControlEvents:controlEvents];
}

-(void)hjt_buttonClick{
    if (self.hjt_buttonEventBlock) {
        self.hjt_buttonEventBlock(self);
    }
}

@end
//使用:
UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(20, 20, 40, 40)];
    btn.backgroundColor = [UIColor redColor];
    [btn setTitle:@"hello" forState:UIControlStateNormal];
    [self.view addSubview:btn];
    
     [btn hjt_addEventHandler:^(UIButton *sender) {
         NSLog(@"%@",sender.titleLabel.text);
         sender.backgroundColor = [UIColor blueColor];
     } forUIControlEvents:UIControlEventTouchUpInside];
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏