将Selector或CodeBlock传递给UIButton事件

时间:2016-11-25 10:32:11

标签: ios uibutton

我有一个创建按钮的addButton方法。我需要将按钮UIControlEventTouchUpInside附加到CodeBlock。

你能做到吗?我还试图传递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];
...

1 个答案:

答案 0 :(得分:0)

您可以传入这样的选择器:

- (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] ;

}

并像这样使用它:

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

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