2016-11-25 60 views
1

我有一个addButton方法创建一个按钮。我需要将按钮UIControlEventTouchUpInside连接到CodeBlock。将选择器或代码块传递给UIButton事件

你能这样做吗?我也试图通过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]; 
... 

回答

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)] ; 
+0

你是对的,感谢这个确认。我曾经尝试过,但是这让我意识到我错过了将目标作为参数传递给实际包含目标方法的实例。 –