2016-11-25 63 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

你是對的,感謝這個確認。我曾經嘗試過,但是這讓我意識到我錯過了將目標作爲參數傳遞給實際包含目標方法的實例。 –