如何dynamic添加UIButton到UITableViewCell?

我想dynamic地添加一个UIButton到一个表格单元格,请看下面的要求。

当用户select一个单元格时,我只是在调整表格单元格的高度

-(void) tableView:(UITableView*) tableView didSelectRowAtIndexPath:(UIIndexPath*) indexPath { selIndPath = [indexPath retain]; [self.tableView beginUpdates]; [self.tableView endUpdates]; } 

上面的方法强制tableView调整所选行的高度。 但是,当我在上面的方法中添加UIButton,该button不可见。

我对[self.tableView reloadData]不感兴趣;

任何帮助不胜感激。

** * ** 编辑 * ** * ***

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { if (selIndPath && selIndPath == indexPath) { //UITableViewCell* cell = [self tableView:tableView cellForRowAtIndexPath:indexPath]; // UIButton* btn = (UIButton*)[[cell contentView] viewWithTag:1234]; // btn.frame = CGRectMake(40, 60, 60, 24); // [cell setNeedsDisplay]; return 90; } return 64; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; [[cell contentView] setBackgroundColor:[UIColor clearColor]]; [[cell backgroundView] setBackgroundColor:[UIColor clearColor]]; } // THIS LINES OF CODE WORKS ONLY ON reloadData if (selIndPath && selIndPath == indexPath) { UIButton* btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; btn.frame = CGRectMake(40, 60, 60, 24); btn.tag = 1234; [btn setTitle:@"Hi" forState:UIControlStateNormal]; [cell.contentView addSubview:btn]; } // Configure the cell. cell.textLabel.text = @"Loading.."; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { selIndPath = [indexPath retain]; [self.tableView deselectRowAtIndexPath:indexPath animated:NO]; //[self.tableView reloadData]; [self.tableView beginUpdates]; [self.tableView endUpdates]; } 

如果将其添加到cellForRowAtIndexPath的单元格中,则添加button将不起作用。 你需要做的是创build一个自定义UITableViewCell (请参考这个问题的答案如何 – 改变定制UIButton在自定义UITableViewCell中的位置 )

在“自定义”单元格中,创build一个方法

 -(void) addButtonToCell { UIButton* btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; btn.frame = CGRectMake(40, 60, 60, 24); btn.tag = 1234; [btn setTitle:@"Hi" forState:UIControlStateNormal]; [self.contentView addSubview:btn]; } 

当然,你如何添加button以及你传递给这个方法的参数取决于你,但是你得到了要点。

cellForRowAtIndexPath :中,只需添加

 if (selIndPath && selIndPath == indexPath) { [cell addButtonToCell]; }