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

后端 未结 9 1186
旧巷少年郎
旧巷少年郎 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:34

    There is a library of blocks additions to the common Foundation/UI classes: BlocksKit. Here is the documentation.

    It does not subclass UIButton, but adds UIControl category:

    [button addEventHandler:^(id sender) {
        //do something
    } forControlEvents:UIControlEventTouchUpInside];
    

    There is also blocks/functional additions to collections (map, filter, etc), views-related stuff and more.

    NOTE: it does not play well with Swift.

    0 讨论(0)
  • 2020-11-29 21:38

    I just implemented this. It work's like a charm!

    And it wasn't even hard.

    typedef void (^ActionBlock)();
    
    @interface UIBlockButton : UIButton {
        ActionBlock _actionBlock;
    }
    
    -(void) handleControlEvent:(UIControlEvents)event
                     withBlock:(ActionBlock) action;
    @end
    
    @implementation UIBlockButton
    
    -(void) handleControlEvent:(UIControlEvents)event
                     withBlock:(ActionBlock) action
    {
        _actionBlock = action;
        [self addTarget:self action:@selector(callActionBlock:) forControlEvents:event];
    }
    
    -(void) callActionBlock:(id)sender{
        _actionBlock();
    }
    @end
    
    0 讨论(0)
  • 2020-11-29 21:45

    There is REKit which brings out Blocks latent ability. It gives you ability to add/override method to a instance using Block.

    With REKit, you can dynamically make a target - which responds to buttonAction - like below:

    id target;
    target = [[NSObject alloc] init];
    [target respondsToSelector:@selector(buttonAction) withKey:nil usingBlock:^(id receiver) {
        // Do something…
    }];
    [button addTarget:target action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
    

    You don't need to make a subclass nor a category.

    In addition to target/action paradigm, you can use REKit for delegation pattern.

    0 讨论(0)
提交回复
热议问题