2013-03-12 132 views
2

我有一個UITableView。根據選擇更改UITableViewCell中按鈕的背景顏色

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
//Where we configure the cell in each row 

static NSString *CellIdentifier = @"Cell"; 
UITableViewCell *cell; 

cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (cell == nil) { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
} 


self.myButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
self.myButton.tag = 5; 
self.myButton.frame = CGRectMake(190.0f, 5.0f, 70.0f, 25.0f); 
self.myButton.layer.borderColor = [UIColor blackColor].CGColor; 
self.myButton.layer.borderWidth = 0.5f; 
self.myButton.backgroundColor = [UIColor grayColor]; 
[self.myButton setTitle:@"Set Active" forState:UIControlStateNormal]; 
[self.myButton addTarget:self action:@selector(myButton:) forControlEvents:UIControlEventTouchUpInside]; 
[cell.contentView addSubview: self.myButton]; 

cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 

} 

-(void) myButton:(id)sender{ 
[sender setBackgroundColor:[UIColor redColor]]; 
} 

假設在tableview部分有3行。我有3行中的按鈕。 在第一個例子中,第一行中的按鈕應該是紅色的,另外兩行應該是灰色的。 如果我選擇第二排中的按鈕,那麼第二排中的按鈕應該是紅色的,另外兩個按鈕應該是灰色的,等等。我還沒有想出辦法做到這一點。有什麼建議麼?

我可以改變我從單元格中選擇的按鈕的顏色。但在同一個實例中,先前選擇的按鈕和所有其他按鈕(除了所選按鈕)應該是默認顏色。每次只有一個按鈕會被高亮顯示,並且在那個時候這將始終是選定的按鈕。

回答

1

我認爲正確的方式來做到這一點 - 子類UITableViewCell和聲明自己的協議,將通知委託在哪個單元按鈕被按下,並在委託 - 通過所有單元格循環,並設置所有的默認顏色和選定的紅色。 我製作demo project

1

簡單的方法是爲每個按鈕設置不同的標籤。像這樣:

button.tag = indexPath.row + c; 

'c'是常數。 而在你的方法:

-(void) myButton:(id)sender{ 
    for(int i=0; i<numberOfRowsInTable; ++i) 
     [(UIButton *)[self.view viewForTag:i+c] setBackgroundColor:[UIColor grayColor]]; 
    [(UIButton *)sender setBackgroundColor:[UIColor redColor]]; 
} 

但是,如果你有2個或表的更多部分這樣可不行

+0

我的問題,是如何將未選中的按鈕設置爲默認顏色。只有選定的按鈕應該是紅色的。 – 2013-03-13 17:08:30

0

就試試這個代碼:

-(void) myButton:(id)sender{ 
    NSLog(@"sender Tag=== %d",[sender tag]); 
    UIButton *btn=(UIButton *)sender; 
    [btn setBackgroundColor:[UIColor redColor ]]; 

} 
+0

我的問題是如何將未選中的按鈕設置爲默認顏色。只有選定的按鈕應該是紅色的。 – 2013-03-13 17:07:42