我有一个带有大量自定义单元格的UITableView
。每个单元都有一个UtilityButton,因此当您从右向左滑动单元时,可以选择Favourite
或Delete
。
同样,当选择“收藏夹”时,utilityButton中的“收藏夹”按钮将变为红色,否则该按钮为“白色”。
问题是在我滚动tableView之后,我选择的单元格最喜欢的按钮(它们曾经是红色的)变成了白色。我想我错过了单元格重用方法中的一些重要内容。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
ColorCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
[cell setNeedsUpdateConstraints];
[cell setRightUtilityButtons:[self rightButtons] WithButtonWidth:58.0f];
cell.delegate = self;
return cell;
}
- (NSArray *)rightButtons
{
NSMutableArray *rightUtilityButtons = [NSMutableArray new];
[rightUtilityButtons sw_addUtilityButtonWithColor:[UIColor colorWithRed:0.78f green:0.78f blue:0.8f alpha:1.0] icon:[UIImage imageNamed:@"heart"]];
[rightUtilityButtons sw_addUtilityButtonWithColor:[UIColor colorWithRed:1.0f green:0.231f blue:0.188 alpha:1.0f] icon:[UIImage imageNamed:@"trash"]];
return rightUtilityButtons;
}
这是单元格的委托方法,将在触发UtilityButton时调用,并显示我如何设置所选按钮的图像,而
heart
是WHITE而heart-selected
是RED。请注意,index == 0
是收藏夹按钮,然后是删除按钮。- (void)swipeableTableViewCell:(ColorCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index
{
NSIndexPath *cellIndexPath = [self.tableView indexPathForCell:cell];
ColorModel *model = [self.objects objectAtIndex:cellIndexPath.row / 2];
if (cellIndexPath.row % 2 == 0) {
switch (index) {
case 0:
{
if ([self.favouriteArray containsObject:model]) {
[self.favouriteArray removeObject:model];
[cell.rightUtilityButtons.firstObject setImage:[UIImage imageNamed:@"heart"] forState:UIControlStateNormal];
}else{
[self.favouriteArray addObject:model];
[cell.rightUtilityButtons.firstObject setImage:[UIImage imageNamed:@"heart-selected"] forState:UIControlStateNormal];
}
[cell hideUtilityButtonsAnimated:YES];
break;
}
case 1:
{
[self.objects removeObjectAtIndex:cellIndexPath.row / 2];
[self.tableView reloadData];
break;
}
}
}
}
谢谢。
最佳答案
滚动表格视图时,将重新加载其单元格,并在cellForRowAtIndexPath
方法中重置/分配一组新的实用程序按钮,在这种情况下,心脏按钮为白色
[cell setRightUtilityButtons:[self rightButtons] WithButtonWidth:58.0f];
代替它,您可以编写如下的
rightButtons
方法,它将解决问题。您也不需要听didTriggerRightUtilityButtonWithIndex
- (NSArray *)rightButtonsForIndexPath:(NSIndexPath *)indexpath
{
NSMutableArray *rightUtilityButtons = [NSMutableArray new];
if (/* row is selected*/) {
[rightUtilityButtons sw_addUtilityButtonWithColor:[UIColor colorWithRed:0.78f green:0.78f blue:0.8f alpha:1.0] icon:[UIImage imageNamed:@"heart-selected"]];
} else {
[rightUtilityButtons sw_addUtilityButtonWithColor:[UIColor colorWithRed:0.78f green:0.78f blue:0.8f alpha:1.0] icon:[UIImage imageNamed:@"heart"]];
}
[rightUtilityButtons sw_addUtilityButtonWithColor:[UIColor colorWithRed:1.0f green:0.231f blue:0.188 alpha:1.0f] icon:[UIImage imageNamed:@"trash"]];
return rightUtilityButtons;
}