Search code examples
iosuitableviewaqgridview

UITableview or AQGridView maintain state of button in cell


As AQGridview borrows a lot of it's ideas from UITableView so I think the answer should apply to both.

I have a custom cell with the following objects inside:

  • label
  • favourite button (can be turned on/off by the user and I use .selected = YES/NO)

The problem is maintain the state of the button when scrolling. Below is my 'cellForItemAtIndex' method.

- (AQGridViewCell *) gridView: (AQGridView *) aGridView cellForItemAtIndex: (NSUInteger) index
{
    static NSString * cellIdentifier = @"CellIdentifier";

    SampleGridViewCell * cell = (SampleGridViewCell *)[aGridView dequeueReusableCellWithIdentifier:cellIdentifier];

    if ( cell == nil )
    {
        cell = [[SampleGridViewCell alloc] initWithFrame: CGRectMake(0.0, 0.0, 200, 60)                                   reuseIdentifier: cellIdentifier];
    }

    NSDictionary *item = [self.items objectAtIndex:index];

    NSString *title = [item objectForKey:@"title"];

    cell.index = index;

    cell.titleLabel.text = title;

    //cell.favButton.selected = (logic goes here);

    return cell;

}

Somehow I need to keep a reference in my viewcontroller of when an item has been favourited so that I can turn the button on/off when the cell is recreated in this method.

Do I do an addTarget on cell.favButton with a method in the vc? But then how do I get a reference to the index of the button?

Has someone implemented something similar?


Solution

  • As you said, add a target to you button to whatever method you want. In that method, you can then get the rows index by using

                  NSSet *touches = [event allTouches];
                  UITouch *touch = [touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:tableview];
          NSIndexPath *indexPath = [tableview indexPathForRowAtPoint: currentTouchPosition];
                  NSUInteger row = [indexPath row];
    

    From there you can then store that the button has been pressed in your existing data set that is being used by the table itself. Then when the table gets loaded, and you retrieve your data, simply enable/disabled the cells button based on the data you've got stored for that row :)