Swift 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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,843评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,538评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,187评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,264评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,289评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,231评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,116评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,945评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,367评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,581评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,754评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,458评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,068评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,692评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,842评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,797评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,654评论 2 354

推荐阅读更多精彩内容