Swift 关于tableView的多选和删除

本文介绍如何使用 Swift 实现 TableView 的基本功能,包括设置代理、数据源、多选操作及右滑删除等功能,并提供了详细的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建表

self.automaticallyAdjustsScrollViewInsets = false;
tableView.frame = CGRect.init(x: 0, y: 64, width: self.view.frame.size.width, height: self.view.frame.size.height);
tableView.backgroundColor = UIColor.white;
self.view.addSubview(tableView);
tableView.delegate = self;
tableView.dataSource = self;
tableView.register(UINib.init(nibName: “WLTableViewCell”, bundle: nil), forCellReuseIdentifier: “WLTableViewCell”);
这里写图片描述
tableView在没有实现DataSource的三个方法是 tableView.dataSource = self; 会报错
//关于tableView的多选操作

 **func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
      return UITableViewCellEditingStyle.init(rawValue: UITableViewCellEditingStyle.insert.rawValue | UITableViewCellEditingStyle.delete.rawValue)!
}**
**//多选选中是的方法
   func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
   //处理选中
   }
   //多选取消选中执行的方法
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
   //处理取消选中
   }**
关于tableView的右滑删除删除的操作
在tableView delegate 的editingStyleForRowAtindexPath 方法中返回
UITableViewCellEditingStyle.delete即可执行多选操作(删除操作有一个必须执行的方法,不执行 删除也不起作用)

删除必须执行的方法
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    print("");
}

如果上面的方法没有执行  侧滑删除无效

在下面的方法中 返回值可以修改删除按钮的文字
func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
return "删除";
}

//tableView 侧滑多个按钮
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
var action1 = UITableViewRowAction();
var action2 = UITableViewRowAction();
var action3 = UITableViewRowAction();
action1 = UITableViewRowAction.init(style: UITableViewRowActionStyle.default, title:”置顶”, handler: { (UITableViewRowAction, IndexPath) in
//执行操作
});
action1.backgroundColor = UIColor.blue;
action2 = UITableViewRowAction.init(style: UITableViewRowActionStyle.default, title:”删除”, handler: { (UITableViewRowAction, IndexPath) in
//执行操作
});
action2.backgroundColor = UIColor.yellow;
action3 = UITableViewRowAction.init(style: UITableViewRowActionStyle.default, title:”隐藏”, handler: { (UITableViewRowAction, IndexPath) in
//执行操作
});
action3.backgroundColor = UIColor.red;
return [action1,action2,action3];
}
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值