【问题标题】:Dynamically adding UIButton to UITableViewCell error将 UIButton 动态添加到 UITableViewCell 错误
【发布时间】:2014-06-20 15:54:00
【问题描述】:

我使用以下代码将 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;
}

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

【问题讨论】:

    标签: ios objective-c uitableview uibutton


    【解决方案1】:

    移动代码以在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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多