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

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

    I find it easy and versatile to use a tiny helper class:

    @interface Handler : NSObject
    
    @end
    
    @implementation Handler {
        void (^block)(id);
    }
    
    + (Handler *)create:(void (^)(id))block {
        Handler *result = [[Handler alloc] init];
    
        result->block = block;
    
        return result;
    }
    
    - (void)call:(id)sender {
        block(sender);
    }
    
    @end
    

    and use it like this:

    Handler *handler = [Handler create:^(id sender) {
        // ... handle the event, using local state captured by the block ...
    }];
    
    // store the handler because the target is not retained in addTarget
    [handlers addObject:handler];
    
    [button addTarget:handler action:@selector(call:) forControlEvents:UIControlEventTouchUpInside];
    

提交回复
热议问题