Bin
Bin

Reputation: 484

Dynamically adding UIButton to UITableViewCell error

I use following code to adding a UIButton to 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;
}

everything is ok when i run this code, but if i scroll the table, the button will add again and again in each cell, like superimposed or each cell has some same buttons superimposed, so how to fix this?

Upvotes: 1

Views: 66

Answers (1)

Stonz2
Stonz2

Reputation: 6396

Move the code to add the button inside the if (cell == nil) statement. This will ensure that the button is only added to new cells, not dequeued cells.

- (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;
}

Upvotes: 4

Related Questions