我有一个包含多个单元格的表格,每个单元格都有一个UIButton
。当我单击该按钮时,按钮单元格背景颜色应该更改。这是我的部分代码供您理解。
当我点击此按钮时,我的所有tableview单元格背景颜色都会发生变化。如何只为选定的单元格做?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = @"SimpleTableCell";
cell = (MenuCell *)[menuTableview dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MenuViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
[cell initState];
// Listens for method calls on cell
cell.delegate = self;
}
if ((self.TempArray.count != 0)) {
for (int i=0; i<TempArray.count; i++) {
if ([self.TableviewArray objectAtIndex:indexPath.row] == TempArray[i]) {
if (cell.backgroundColor != [UIColor lightGrayColor]) {
cell.backgroundColor = [UIColor lightGrayColor];
}
UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
button.tag=indexPath.row;
[button addTarget:self action:@selector(aMethod:) forControlEvents:UIControlEventTouchDown];
[button setTitle:@"UnHide" forState:UIControlStateNormal];
button.frame = CGRectMake(200.0, 20.0, 160.0, 40.0);
[cell.contentView addSubview:button];
}
}
}
// Set index for this cell (it could be wrong if cell is re-used)
cell.downloadIndex = (int)indexPath.row;
Download *download = [TableviewArray objectAtIndex:indexPath.row];
cell.downloading = download.downloading;
cell.completed = download.completed;
cell.MenuLang.text = download.name;
cell.downLoadPrgView.progress = download.percentageDownloaded;
// Check for completed status
cell.completed = download.completed;
cell.CompletedMenuLang.text = download.name;
return cell;
}
-(void)aMethod:(UIButton*)sender {
NSLog(@"I Clicked a button %d",sender.tag);
int row = sender.tag;
}
答案 0 :(得分:0)
tableView.rowHeight = UITableViewAutomaticDimension
使用此单元格的索引路径进行更改
答案 1 :(得分:0)
这是我的回答..
-(void)aMethod:(UIButton*)sender
{
NSLog(@"I Clicked a button %d",sender.tag);
int row = sender.tag;
NSIndexPath *path = [NSIndexPath indexPathForRow:row inSection:0];
UITableViewCell *cell = [menuTableview cellForRowAtIndexPath:path];
cell.contentView.backgroundColor = [UIColor whiteColor];
}
答案 2 :(得分:0)
只需实现下面的代码,您就可以更改特定单元格的背景颜色以及隐藏所选按钮。
-(void)aMethod:(UIButton*)sender {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag inSection:0];
Friends1TableViewCell *cell = (Friends1TableViewCell *)[self.tblVW cellForRowAtIndexPath:indexPath];
cell.backgroundColor = [UIColor redColor];
sender.hidden = YES;
}
答案 3 :(得分:0)
试试这个
@property (nonatomic, assign) NSInteger selectedRow;
self.selectedRow = -1; // init with -1
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// ...
if(self.selectedRow == indexPath.row) {
cell.backgroundColor = SELECTED_COLOR;
}
else {
cell.backgroundColor = NORMAL_COLOR;
}
return cell;
}
-(void)aMethod:(UIButton*)sender {
// ...
self.selectedRow = row;
[self.myTableView reloadData];
}