iOS tableViewCell 自定义左滑删除按钮样式

  • iOS11之前

for (UIView *subView in self.subviews) {
        if ([subView isKindOfClass:NSClassFromString(@"UITableViewCellDeleteConfirmationView")]) {
            for (UIButton *btn in subView.subviews) {
                if ([btn isKindOfClass:[UIButton class]]) {
/*在此处可以自定义删除按钮的样式*/
                    btn.titleLabel.font = [UIFont systemFontOfSize:15.0f];
                }
            }
        }
    }

将上边⤴️代码加入到 自定义cell.m 文件 layoutSubviews 方法中!!!之外还要设置tableview的代理方法

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return   UITableViewCellEditingStyleDelete;
}
//Cell可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
//修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}
//设置进入编辑状态时,Cell不会缩进
- (BOOL)tableView: (UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.arr removeObjectAtIndex:indexPath.row];
    [self.mainTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
  • 补充:(iOS 11 之后)

    • 只需要设置tableview一个代理方法可以更加方便的实现以上功能

    码:

#pragma mark 测试
- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath{
    //删除
    if (@available(iOS 11.0, *)) {
        UIContextualAction *delete = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"删除" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
            [self.arr removeObjectAtIndex:indexPath.row];
            completionHandler (YES);
            [self.mainTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }];
//    delete.image = [UIImage imageNamed:@"delete"];//这里还可以设置图片
    delete.backgroundColor = [UIColor grayColor];
    UISwipeActionsConfiguration *config = [UISwipeActionsConfiguration configurationWithActions:@[delete]];
    return config;
    } else {
        return nil;
        // Fallback on earlier versions
    }
}
  • cell加载动画

只要在代理方法中加入动画代码即可

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.x = - SCREEN_WIDTH;
    cell.alpha = 0.1;
    [UIView animateWithDuration:0.8 animations:^{
        cell.x = 0;
        cell.alpha = 1;
    }completion:^(BOOL finish){
    
    }];
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容