【问题标题】:Table view cell background goes white when deleting a cell - iOS删除单元格时表格视图单元格背景变白 - iOS
【发布时间】:2018-03-08 20:58:19
【问题描述】:

我有一个带有UITableView 的iOS 应用程序,我注意到当用户选择Delete 按钮时,单元格背景颜色会闪烁白色。

editActionsForRowAtIndexPath 方法中,我创建了两个单元格按钮:EditDelete。第一个按钮的样式设置为UITableViewRowActionStyleNormal。但是第二个按钮的样式设置为UITableViewRowActionStyleDestructive - 我注意到只有当样式设置为破坏性时才会出现此问题。有谁知道为什么会这样?

这是我用来设置单元格操作按钮的方法:

-(NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // Create the table view cell edit buttons.
    UITableViewRowAction *editButton = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"Edit" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        // Edit the selected action.
        [self editAction:indexPath];
    }];
    editButton.backgroundColor = [UIColor blueColor];
    
    UITableViewRowAction *deleteButton = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"Delete" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        // Delete the selected action.
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }];
    
    return @[deleteButton, editButton];
}

当用户滚动、点击它或当他/她选择Edit按钮时,单元格的颜色是正常的,但是当他们选择Delete按钮时,单元格变成白色,因为删除动画正在发生.

我该如何解决这个问题?

【问题讨论】:

标签: objective-c uitableview uicolor nsindexpath uitableviewrowaction


【解决方案1】:

事实证明,我遇到的问题是由于 iOS 错误造成的。我在这里找到了解决方案:https://stackoverflow.com/a/46649768/1598906

[[UITableViewCell appearance] setBackgroundColor:[UIColor clearColor]];

上面的代码是在 App Delegate 中设置的,它将背景颜色设置为清除,从而去除了白色背景视图。

【讨论】:

    【解决方案2】:

    在调用deleteRowsAtIndexPaths方法之前,需要从数据源中移除对象;

    替换这个:

    UITableViewRowAction *deleteButton = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"Delete" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
    
            // Delete the selected action.
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }];
    

    类似这样的:

    UITableViewRowAction *deleteButton = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"Delete" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
    
            // Delete the selected action.
            [self deleteObjectAtIndexPath:indexPath];
        }];
    

    及删除方法:

    - (void)deleteObjectAtIndexPath:(NSIndexPath *)indexPath {
        // remove object from data source. I assume that you have an array dataSource, or change it according with your data source
        [self.dataSource removeObjectAtIndex:(indexPath.row)];
    
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    

    【讨论】: