UITableViewCell and UIButton issue

Discussion in 'iOS Programming' started by final1cut, Apr 3, 2009.

  1. macrumors newbie

    Joined:
    Apr 3, 2009
    #1
    Hi
    I have a custom UITableViewCell and in there except from other elements i want to draw two buttons which once either pressed the one animates a transformation on the button and the other changes picture(actual actions dont matter that much).What happens is that except for the cell in which the button was pressed i see the effect in other cells too.
    Also if i use an animation i see the transformed button drawn behind the normal one..one on top of the other
    to be more precise heres a sample of my code:

    Code:
    - (UITableViewCell *)tableView:(UITableView *)tableView 
    		 cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    	AnswerView * cell = (AnswerView *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    	UIButton * thumbsUp;
    	if(cell == nil)
    	{
    		cell = [[[AnswerView alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    		button= [[[UIButton  alloc] initWithFrame:CGRectMake(x, y, w, 
    															   h)]autorelease];
    		button.tag = 2;
    		[button addTarget:self action:@selector(clicked:) forControlEvents:UIControlEventTouchUpInside];
    	}
    	else
    		button = (UIButton *)[cell.contentView viewWithTag:2];
    
    if(/* some logic involving indexPath.row */)
     [button setFrame: ] 
    else
    [button setFrame:
    
    ...
    [cell.contentView addSubView:button];
    return cell;
    }
    Is this a completely the wrong way to go ?
     
  2. macrumors 68030

    johnnyjibbs

    Joined:
    Sep 18, 2003
    Location:
    London, UK
    #2
    Since you have subclassed the cell, why don't you stick the buttons and all the cell layout into your AnswerView class? That way, you'll just be adding and removing AnswerView cell objects rather than keeping the buttons and cells seperately.

    At the moment, I think you are running into problems when the cells are reused and you may also have a memory leak, which is why the buttons are building up on top of each other.
     
  3. thread starter macrumors newbie

    Joined:
    Apr 3, 2009
    #3
    thnks for the reply...
    i noticed a pattern in how the button is wrongly drawn in other cells and its every other 2 cells.Does this has to do with how the cells are reused?
     
  4. macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #4
    You need to addSubview the button inside the block of code where you create the cell and button. Your code is adding the subview every time, which isn't correct when reusing the cell.
     

Share This Page