动态地将UIButton添加到UITableViewCell错误

时间:2014-06-20 15:54:00

标签: ios objective-c uitableview uibutton

我使用以下代码将UIButton添加到UITableViewCell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *CellIdentifier = @"Cell";
  MainCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if (cell == nil) {
    cell = [[MainCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
  }

  self.btnMessage = [[UIButton alloc] initWithFrame:CGRectMake(20, 300, 54, 15)];
  [self.btnMessage setBackgroundImage:[UIImage imageNamed:@"message.png"] forState:UIControlStateNormal];
  [self.btnMessage addTarget:self action:@selector(messageButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
  [self.btnMessage setTitle:@"Message" forState:UIControlStateNormal];
  self.btnMessage.titleLabel.font = [UIFont systemFontOfSize:12.0f];
  [self.btnMessage setTitleEdgeInsets:UIEdgeInsetsMake(0, 12, 0, 0)];
  [cell addSubview:self.btnMessage];

  return cell;
}

当我运行此代码时一切正常,但是如果我滚动表格,按钮将在每个单元格中反复添加,如叠加或每个单元格都有相同的按钮叠加,那么如何解决这个问题呢?

1 个答案:

答案 0 :(得分:4)

移动代码以在if (cell == nil)语句中添加按钮。这将确保按钮仅添加到新单元格,而不是添加到出列单元格。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *CellIdentifier = @"Cell";
  MainCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if (cell == nil) {
    cell = [[MainCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    self.btnMessage = [[UIButton alloc] initWithFrame:CGRectMake(20, 300, 54, 15)];
    [self.btnMessage setBackgroundImage:[UIImage imageNamed:@"message.png"] forState:UIControlStateNormal];
    [self.btnMessage addTarget:self action:@selector(messageButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.btnMessage setTitle:@"Message" forState:UIControlStateNormal];
    self.btnMessage.titleLabel.font = [UIFont systemFontOfSize:12.0f];
    [self.btnMessage setTitleEdgeInsets:UIEdgeInsetsMake(0, 12, 0, 0)];
    [cell addSubview:self.btnMessage];
  }

  return cell;
}