2015-11-05 88 views
0

我在下面的代碼上創建了for循環的一些按鈕。帶IBAction的IOS UIButton

UIView *buttonsView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _viewEmoji.frame.size.width, 35)]; 
    [buttonsView setBackgroundColor:[UIColor greenColor]]; 
for (int i = 0; i < myObject.count; i ++) { 
     UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
     [button setFrame:CGRectMake(35*i + 5, 0, 35, 35)]; 
     [button setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@", [myObject objectAtIndex:i]]] forState:UIControlStateNormal]; 
     [button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside]; 
     [buttonsView addSubview:button]; 
    } 

現在,我如何點擊按鈕來處理事件。

每個按鈕被點擊,它將處理1個事件。例如:如果我有2個按鈕是由for循環創建的。當我點擊按鈕1,它會記錄1,當我點擊按鈕2,它會記錄2.

+3

每個按鈕提供一個獨特的'tag'值。 – rmaddy

回答

1

不喜歡

UIView *buttonsView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _viewEmoji.frame.size.width, 35)]; 
[buttonsView setBackgroundColor:[UIColor greenColor]]; 
for (int i = 0; i < myObject.count; i ++) { 
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
    [button setFrame:CGRectMake(35*i + 5, 0, 35, 35)]; 
    [button setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@", [myObject objectAtIndex:i]]] forState:UIControlStateNormal]; 
    [button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside]; 
    // set the tag for identify which button you pressed 
    button.tag = i; // else use --> [myObject objectAtIndex:i] 
    [buttonsView addSubview:button]; 
} 

    //here add your buttonsView to mainview 
self.view addsubview(buttonsView) 

// for button action 
-(void)clickButton:(UIButton*)sender 
{ 
    NSLog(@" Index: %d ", sender.tag); 
    [sender setBackgroundImage:[UIImage imageNamed:@"XXX.png"] forState:UIControlStateNormal]; 

} 
+3

我建議將每個按鈕的標籤設置爲「i + 1」或其他避免給按鈕標籤爲「0」的計算。 – rmaddy

+0

天啊!這是很樣品。謝謝。 –

+0

簡單的兄弟,**發件人**是你當前選擇的按鈕,你可以爲你選擇的按鈕做任何事情,即所有 –