2012-01-04 70 views
0

我正在重複使用動態構建UIButton的一些代碼(沒有界面構建器)。我使用addTarget:action:forControlEvents方法在每次按下按鈕時執行操作。我根據setSelected和isSelected屬性更改按鈕的背景顏色。訪問動態構建的按鈕

我添加了一個重置​​按鈕,以便一次取消選擇所有按鈕。但是,我很難確定如何訪問動態添加按鈕的屬性。

代碼來創建按鈕是如下:

for(int y = 1; y < 10; y++) 
{ 

    for(int x = 1; x < 5; x++){ 
     z++; 

     aButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
     aButton.frame = CGRectMake(x*x_plot, y_plot, 60, 40); 
     [aButton setBackgroundImage:[UIImage imageNamed:@"btnUnselected.png"] forState:UIControlStateNormal]; 
     [aButton addTarget:self action:@selector(digitClick:) forControlEvents:UIControlEventTouchUpInside]; 
     [aButton setTitle:[NSString stringWithFormat:@"%d",z] forState:UIControlStateNormal]; 
     aButton.titleLabel.textColor = [UIColor blackColor]; 
     aButton.tag = z; 
     [self.view addSubview:aButton]; 
    } 
    y_plot=y_plot+45; //make a 4x9 grid of buttons 
} 
+1

你設置了'tag',所以你應該能夠做'UIButton * butt =(UIButton *)[self.view viewWithTag:tag]'? – 2012-01-04 03:32:38

+0

謝謝,邁克!完美工作! – 2012-01-04 04:03:37

回答

0

你可以使用這樣的代碼要經過所有的子視圖

NSArray *ar = self.view.subviews; 
[ar enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 
    if ([obj isKindOfClass:[UIButton class]]) 
    { 
     NSLog(@"I've got 'obj' that is a UIButton on the screen!!!!"); 
    } 
}];