UITableView中,如何在多个Section间,移动、删除、插入Cell

本文主要介绍UITableView中,如何在多个Section间,移动、删除、插入Cell

UITableView为我们提供了以下几个函数,从参数类型可以看出,可以同时插入删除多个Cell或Section,但移动只能移动一个Cell或Section。
open func insertRows(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation)
open func insertSections(_ sections: IndexSet, with animation: UITableViewRowAnimation)

open func deleteRows(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation)
open func deleteSections(_ sections: IndexSet, with animation: UITableViewRowAnimation)

@available(iOS 5.0, *)
open func moveRow(at indexPath: IndexPath, to newIndexPath: IndexPath)
@available(iOS 5.0, *)
open func moveSection(_ section: Int, toSection newSection: Int)
效果图如下
效果图

左滑删除

TableView中提供了 editActionsForRowAt indexPath这个方法,可以添加左滑按钮,但具体的删除操作需要我们自己完成。从这个函数的返回值中可以看出,我们能够添加多个按钮。但关于左滑按钮的自定义,我们可以直接控制按钮的背景颜色和文字颜色,若想添加按钮图片,可以直接在cell右侧添加一张图片覆盖左滑按钮。
@available(iOS 8.0, *)
optional public func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? 

代码如下

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let deleteAction = UITableViewRowAction(style: .destructive, title: "删除") { (action, actionIndexPath) in
        //删除操作
    }
    let otherAction = UITableViewRowAction(style: .destructive, title: "其他") { (action, actionIndexPath) in
        //其他操作
    }
    return [deleteAction]
}
注意事项

在删除操作前,我们需要对TableView的数据进行操作。在调用deleteRows时,会自动调用numberOfRowsInSection和numberOfSections这两个函数。即系统会判断删除操作前,cell和section的个数是否已经修改,若未修改会直接crash并提示以下错误。另外,当删除最后一个Cell时,不能调用deleteRows而应该调用deleteSections。

reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (6) must be equal to the number of rows contained in that section before the update (6), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

代码如下
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    //创建删除操作
    let deleteAction = UITableViewRowAction(style: .destructive, title: "删除") { (action, actionIndexPath) in
        if indexPath.section == 0 && self.dataArray1.count != 0 { //判断删除的是哪个section的cell
            self.dataArray1.remove(at: indexPath.row)
            ///注意: 修改数据后判断当前section是否已经没有数据,若没有则需要删除整个section,若删除cell会报错
            if self.dataArray1.count == 0 {
                tableView.deleteSections([0], with: .automatic)
            } else {
                tableView.deleteRows(at: [indexPath], with: .automatic)
            }
        } else {
            self.dataArray2.remove(at: indexPath.row)
            if self.dataArray2.count == 0 { //同上
                tableView.deleteSections([indexPath.section], with: .automatic)
            } else {
                tableView.deleteRows(at: [indexPath], with: .automatic)
            }
        }
    }
    return [deleteAction]
}

Cell的移动和插入

TableView提供一下四个函数用于移动和插入Cell,这里需要注意的地方跟删除一样。在移动和插入之前需要先对数据进行操作,若没有修改cell的行数和对应的section个数,就这会crash。移动Cell还有一个需要注意的地方,在移动Section中最后一个Cell或将一个Cell移动到新的Section时,不能调用moveRow函数,需要将移动操作拆分为插入和删除操作。因为在新增第一个Cell或删除最后一个Cell,调用moveRow函数时,cell的indexpath已经做了更改,这时系统认为将一个cell移动到一个不存在的位置,直接crash。插入操作和删除操作类似,若Section在插入前并没有Cell,需要调用insertSections来完成插入。

@available(iOS 5.0, *)
open func moveRow(at indexPath: IndexPath, to newIndexPath: IndexPath)
@available(iOS 5.0, *)
open func moveSection(_ section: Int, toSection newSection: Int)

open func insertRows(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation)
open func insertSections(_ sections: IndexSet, with animation: UITableViewRowAnimation)
点击TableView时移动Cell
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    //点击时,将cell移动到另一个section
    if indexPath.section == 0 && dataArray1.count != 0 {
        let titleString = dataArray1[indexPath.row]
        dataArray1.remove(at: indexPath.row)
        
        //注意删除一条数据后,若该Section数据个数为0,即Cell个数为0时,需要删除整个Section
        //同时无法再使用moveRow函数,因为Section有变化,需要调用insertRows来完成移动操作
        if dataArray1.count == 0 {
            //删除section
            tableView.deleteSections([0], with: .top)
            //更新数据
            dataArray2.insert(titleString, at: 0)
            //判断是否是添加一个新的Section
            if dataArray2.count == 1 { //添加一个Section
                tableView.insertSections([1], with: .top)
            } else {
                //更新数据后,插入cell
                tableView.insertRows(at: [IndexPath(item: 0, section: 0)], with: .top)
            }
        } else {
            if dataArray2.count == 0 { //添加一个Section
                //先做删除修改
                tableView.deleteRows(at: [indexPath], with: .fade)
                //删除完成后,插入数据,并触发插入动画
                dataArray2.insert(titleString, at: 0)
                tableView.insertSections([1], with: .top)
            } else {
                dataArray2.insert(titleString, at: 0)
                tableView.moveRow(at: indexPath, to: IndexPath(item: 0, section: 1))
            }
        }

    } else {
        let titleString = dataArray2[indexPath.row]
        dataArray2.remove(at: indexPath.row)
        if dataArray2.count == 0 {
            var deleteSection = 1 ///判断当前是哪一个Section
            if indexPath.section == 0 {
                deleteSection = 0
            }
            tableView.deleteSections([deleteSection], with: .fade)
            dataArray1.insert(titleString, at: 0)
            if dataArray1.count == 1 { //添加一个Section
                tableView.insertSections([0], with: .top)
            } else {
                tableView.insertRows(at: [IndexPath(item: 0, section: 0)], with: .top)
            }
        } else {
            if dataArray1.count == 0 { //添加一个Section
                tableView.deleteRows(at: [indexPath], with: .bottom)
                dataArray1.insert(titleString, at: 0)
                tableView.insertSections([0], with: .top)
            } else {
                dataArray1.insert(titleString, at: 0)
                tableView.moveRow(at: indexPath, to: IndexPath(item: 0, section: 0))
            }
        }
    }
}

总结

个人认为,可以将移动删除插入这几个动作,看成是系统为TableView刷新添加了一个动画。我们在执行这几个动画前,已经对数据进行了修改,然后添加动画展示给用户看,当然如果直接调用reloadData也可以实现效果,只是没有动画而已。这里需要注意一点,这几个动作都只会重新调用numberOfRowsInSection和numberOfSections这两个函数,并不会执行cellForRowAt indexPath,因此如果在cellForRow中进行移动删除和插入操作时,需要重新获取indexpath



作者:NFatalist
链接:https://www.jianshu.com/p/f660f9b1534c
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在iOS,一个视图只能有一个UITableView。但是可以通过创建多个UITableView来实现一个视图显示多个表格的效果。以下是一个示例代码: 首先,你需要在视图控制器添加多个UITableView的实例变量: ```swift class YourViewController: UIViewController { var tableView1: UITableView! var tableView2: UITableView! // ... } ``` 然后,在视图加载完成后,你可以创建和配置这些UITableView的实例: ```swift override func viewDidLoad() { super.viewDidLoad() // 创建第一个UITableView tableView1 = UITableView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height/2)) tableView1.dataSource = self tableView1.delegate = self view.addSubview(tableView1) // 创建第二个UITableView tableView2 = UITableView(frame: CGRect(x: 0, y: view.frame.height/2, width: view.frame.width, height: view.frame.height/2)) tableView2.dataSource = self tableView2.delegate = self view.addSubview(tableView2) // ... } ``` 接下来,你需要实现UITableViewDataSource和UITableViewDelegate协议的相关方法来提供表格的数据和处理交互事件。例如: ```swift extension YourViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView == tableView1 { // 返回第一个UITableView的行数 return 10 } else if tableView == tableView2 { // 返回第二个UITableView的行数 return 5 } return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) if tableView == tableView1 { // 配置第一个UITableView的单元格 cell.textLabel?.text = "Table View 1 - Row \(indexPath.row)" } else if tableView == tableView2 { // 配置第二个UITableView的单元格 cell.textLabel?.text = "Table View 2 - Row \(indexPath.row)" } return cell } } extension YourViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if tableView == tableView1 { // 处理第一个UITableView的行选事件 print("Table View 1 - Row \(indexPath.row) selected") } else if tableView == tableView2 { // 处理第二个UITableView的行选事件 print("Table View 2 - Row \(indexPath.row) selected") } } } ``` 这样,你就可以在同一个视图使用多个UITableView了。记得在视图控制器遵循UITableViewDataSource和UITableViewDelegate协议,并在视图加载完成后设置数据源和代理。 希望这能帮到你!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值