Chris G. Chris G. - 15 days ago 5
iOS Question

Passing a Selector or CodeBlock to UIButton events

I have a

addButton
method that creates a button. I need the buttons
UIControlEventTouchUpInside
to be attached to a CodeBlock.

Can you do that? I have also tried to pass in a
SEL(selector)
.

typedef void (^menuAction)();

- (void) addButton:(NSString*)title callback:(menuAction)action{
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:@selector(action)
forControlEvents:UIControlEventTouchUpInside];
...

shm shm
Answer

You can pass in a selector like this:

- (void) addButton:(NSString*)title withSelector:(SEL)selector {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    // set some frame
    CGRect f = CGRectMake(10, 10, 200, 200);
    [button setFrame:f] ;

    [button setTitle:title forState:UIControlStateNormal] ;

    [button addTarget:self
               action:selector
     forControlEvents:UIControlEventTouchUpInside];

    // add to view
    [self.view addSubview:button] ;

}

and use it like this:

-(void)doStuff {
    NSLog(@"doStuff");
}

[self addButton:@"some button" withSelector:@selector(doStuff)] ;