Search code examples
iphoneobjective-cipaduitableviewios6

Button in UITableView is appearing twice in iPad Master View Controller


Created a UITableView programmatically, data in my tableview in iPad Master View Controller is loaded dynamically, i am putting a button in the last cell, but the button is showing up again in the tableview underneath the cell... First time when the code is executed, the button appears only once, but next time it shows up twice... Here is the code...

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

if([_objects count] > 1)
{

    if(indexPath.row == [_objects count])
    {            

        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

        //set the position of the button
        button.frame = CGRectMake(cell.frame.origin.x + 50, cell.frame.origin.y + 15, 225, 30);
        [button setTitle:@"Hide me" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(customActionPressed) forControlEvents:UIControlEventTouchUpInside];
        button.backgroundColor= [UIColor clearColor];
        [cell.contentView addSubview:button];

    }
    else
    {
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
        cell.textLabel.textColor = [UIColor colorWithRed:0/255.0 green:100.0/255.0 blue:220.0/255.0 alpha:1.0];
        cell.textLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:13];
        cell.textLabel.text = [_objects objectAtIndex:indexPath.row];
        NSLog(@"%@", [_objects objectAtIndex:indexPath.row]);
    }
}

return cell;
}

for ex:: here is a snapshot of the tableview (how can i put the image here???)

  1. aaa
  2. bbb
  3. ccc
  4. ddd
  5. eee
  6. UIButton

    UIButton is appearing again here in the tableview

    Here is the image link http://s10.postimg.org/fwarb2661/i_OS_Simulator_Screen_shot_28_Dec_2013_10_57_32_A.png

    any help is appreciated, thanks in advance..


Solution

  • Please write bellow code :

     if (cell)
    
       {
    
         cell =nil;
    
       }
    

    before creating your tableview cell

     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    

    //write here

    if (cell)
    
       {
    
         cell =nil;
    
       }
    

    //*

    if (cell == nil) {
    
       cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
      }