UIButton block equivalent to addTarget:action:forControlEvents: method?

后端 未结 9 1207
旧巷少年郎
旧巷少年郎 2020-11-29 20:58

I looked around, but couldn\'t find this on the internet, nor anywhere in the Apple docs, so I\'m guessing it doesn\'t exist.

But is there a iOS4 blocks equivalent A

9条回答
  •  一向
    一向 (楼主)
    2020-11-29 21:28

    Here's a working category implementation. In it's current form, this should only be used in DEBUG. I use this category in conjunction with a function (included below) to test various bits of code when user interaction and timing are important. Again this is only for development/debug purposes and shouldn't be considered for production, hence the #ifdef DEBUG ;)

    #ifdef DEBUG
    
    #import 
    
    static char UIButtonBlockKey;
    
    @interface UIButton (UIBlockButton)
    
    - (void)handleControlEvent:(UIControlEvents)event withBlock:(ActionBlock)block;
    - (void)callActionBlock:(id)sender;
    
    @end
    
    
    @implementation UIButton (UIBlockButton)
    
    - (void)handleControlEvent:(UIControlEvents)event withBlock:(ActionBlock)block {
        objc_setAssociatedObject(self, &UIButtonBlockKey, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
        [self addTarget:self action:@selector(callActionBlock:) forControlEvents:event];
    }
    
    
    - (void)callActionBlock:(id)sender {
        ActionBlock block = (ActionBlock)objc_getAssociatedObject(self, &UIButtonBlockKey);
        if (block) {
            block();
        }
    }
    
    @end
    
    
    void DSAddGlobalButton(NSString *title, ActionBlock block) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button setTitle:title forState:UIControlStateNormal];
        [button handleControlEvent:UIControlEventTouchUpInside withBlock:block];
        [button sizeToFit];
        [button setFrame:(CGRect){{100.0f, 100.0f}, [button frame].size}];
    
        UIView *firstView = [[[[UIApplication sharedApplication] keyWindow] subviews] objectAtIndex:0];
        [firstView addSubview:button];
    }
    
    
    #endif
    

提交回复
热议问题