我有一个UITableView
,其中包含大量自定义单元格。每个单元格都有一个utilityButton,因此当您从右向左滑动单元格时,您可以选择Favourite
或Delete
。
此外,当选择收藏夹时,utilityButton中的收藏夹按钮将变为 RED ,否则按钮为 WHITE 。
问题是在我滚动tableView之后,我选择的单元格最喜欢的按钮(它们曾经 RED )变成 WHITE 。我想我错过了一些重要的细胞重用方法。
- (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;
}
}
}
}
感谢。
答案 0 :(得分:1)
当您滚动表格视图时,它会重新加载其单元格,而在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;
}
答案 1 :(得分:0)
那是因为细胞重用。您应该根据是否在- (NSArray *)rightButtons
中受欢迎来设置按钮的正确颜色。