Slee
Slee

Reputation: 28268

update UITableViewCell appearance when button inside cell is tapped

I have a UITableView with a fairly complex layout, inside it are a plus and a minus sign that allow you to add and subtract values from the cell row.

Here is my code so far:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSString *CellIdentifier =@"Cell"; //[NSString stringWithFormat: @"Cell%@",[[self.purchaseOrderItems objectAtIndex:indexPath.row] ItemID]] ;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) 
    {
      cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];  
    } 
    return [self styleCell:cell withIndexPath:indexPath];    
}

And styling the cell:

    -(UITableViewCell *) styleCell: (UITableViewCell *) cell withIndexPath: (NSIndexPath *) indexPath {

        cell.tag = indexPath.row;
       // a bunch of layout code goes here along with my button
       UIButton *addBtn = [[[UIButton alloc] initWithFrame:CGRectMake(self.itemsTableView.frame.size.width-247, 35, 38, 33)] autorelease];
       [addBtn setBackgroundImage:[UIImage imageNamed:@"btn-cart-add"] forState:UIControlStateNormal];
       [addBtn setTag:cell.tag];
       [addBtn addTarget:self action:@selector(handleAddTap:) forControlEvents:UIControlEventTouchUpInside];

       // note I have the same tag on the cell as the button

    }

and my code for handling the tap:

- (void)handleAddTap:(id)sender {  
    UIButton *btn = (UIButton *) sender;
    PurchaseOrderItem *item = [[[PurchaseOrderDataSource sharedPurchaseOrderDataSource] purchaseOrderItems] objectAtIndex:btn.tag];
    [[PurchaseOrderDataSource sharedPurchaseOrderDataSource] AddUpdatePurchaseOrderItem:item.ItemID WithQty:[NSNumber numberWithInt:[item.Qty intValue] + 1 ]];
    UITableViewCell *cell =(UITableViewCell *) [[btn superview ] superview];
   [cell setNeedsLayout];

}

I was hoping that setting setNeedsLayout would do the redraw but nothing happens,if I simply reload the table this works great but on large amounts of rows it gets very clunky. Also if I scroll this row out of view and then back again it is updated properly.

How do I get just this row to update without reloading the whole table or having to scroll off and back on the screen again?

Upvotes: 0

Views: 941

Answers (1)

mhunter007
mhunter007

Reputation: 114

You can have the row update by calling reloadRowsAtIndexPath. You can build the IndexPath based on the cell.tag you're setting in addBtn.tag

NSIndexPath *myip = [[NSIndexPath alloc] indexPathForRow:sender.tag inSection:0];
NSArray *nsa = [[NSArray alloc] initWithObjects:myip, nil];
[thisTableView reloadRowsAtIndexPaths:nsa withRowAnimation:UITableViewRowAnimationFade];

Upvotes: 2

Related Questions