views:

838

answers:

1

For every entry in the table view cell, I need a button at right then some text and again a button at the left. At the button click event I need to change the text (left/right button clicked.) and remove either of the buttons depending on the text conditions. I am not able to remove the buttons using cellForRowAtIndexPath method. I tried subclassing the UITableViewCell and use method -prepareForReuse but I can't reset the cell. Any ideas how do I achieve this? Or is there some way to make this button invisible or may be hide?

    NSString *CellIdentifier = [[NSString alloc] initWithFormat:@"Cell%d",indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}


[self.tableView clearsContextBeforeDrawing];
NSString *str = [listOfItems objectAtIndex:indexPath.row];

    cell.text = [listOfItems objectAtIndex:indexPath.row];
 cell.textColor = [UIColor blueColor];
 cell.font = [UIFont systemFontOfSize:14];

  UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];  
  UIImage *image = [UIImage imageNamed:@"Arrow_Right.png"];
  CGRect frame = CGRectMake(290, 5, image.size.width, image.size.height);
  button.frame = frame; 
  [button setBackgroundImage:image forState:UIControlStateNormal];
  button.backgroundColor = [UIColor clearColor];
  [button addTarget:self action:@selector(rightArrow_clicked:) forControlEvents:UIControlEventTouchUpInside];
  [cell addSubview:button];

  UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];  
  UIImage *img = [UIImage imageNamed:@"Arrow_Left.png"];
  CGRect frame1 = CGRectMake(5, 5, img.size.width, img.size.height);
  button1.frame = frame1;
  [button1 setBackgroundImage:img forState:UIControlStateNormal];
  button1.backgroundColor = [UIColor clearColor];
  [button1 addTarget:self action:@selector(leftArrow_clicked:) forControlEvents:UIControlEventTouchUpInside];
  [cell addSubview:button1];

 if([str isEqual:@" abc  "])
  [button setEnabled:NO];
 if([str isEqual:@" pqr "])
  [button1 setEnabled:NO];
+1  A: 

What you'll want to do is subclass UITableViewCell, and add the subviews in the init method so that they're only added once.

What's most likely happening is you're adding subviews to a reusable cell, which most likely already has buttons on it from a previous use. In addition, you can set the buttons to "invisible" like so:

[button setHidden:YES];
craig