UITableview或AQGridView维护单元格中的按钮状态

时间:2012-05-30 00:03:16

标签: ios uitableview aqgridview

由于AQGridview从UITableView借用了很多想法,所以我认为答案应该适用于两者。

我有一个自定义单元格,其中包含以下对象:

  • 标签
  • 最喜欢的按钮(可以由用户打开/关闭,我使用.selected = YES / NO)

问题是滚动时保持按钮的状态。下面是我的'cellForItemAtIndex'方法。

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

}

不知何故,我需要在我的viewcontroller中保留一个项目已被优惠的参考,以便在此方法中重新创建单元格时可以打开/关闭按钮。

我是否使用vc中的方法在cell.favButton上执行addTarget?但是,如何获得对按钮索引的引用?

有人实施了类似的东西吗?

1 个答案:

答案 0 :(得分:0)

正如你所说,将目标添加到你想要的任何方法按钮。在该方法中,您可以使用

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

然后,您可以在此处存储按钮已在表本身正在使用的现有数据集中按下。 然后当表加载并检索数据时,只需根据您为该行存储的数据启用/禁用单元格按钮:)