【问题标题】:Delete last row in section of UITableView without deleting section?删除 UITableView 部分的最后一行而不删除部分?
【发布时间】:2015-07-28 17:00:43
【问题描述】:

有什么方法可以在不删除整个部分的情况下删除 UITableView 中特定部分的最后一行?我希望能够从一个部分中删除最后一行,但保持该部分的标题可见,因为它表明这些部分存在但没有数据。

我在 StackOverflow 上找到了多个先前的答案,但他们的解决方案似乎都是如果要删除部分的最后一行,则必须删除该部分,例如,How to delete the last row of a section?

【问题讨论】:

    标签: ios uitableview cocoa-touch


    【解决方案1】:

    嗯,您的问题与 UITableViewDataSource 协议的工作原理有关,如果该部分中没有任何内容,则不应显示该部分。

    但是你能做些什么呢?

    有一个简单的方法,在你的 dataSource numberOfRowsInSection 中你可以做一个 if,那个条件将验证你的 dataSource 计数是否等于 0 并返回 1,像这样:

        func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            var numberOfRows = 0
            switch section{
            case 0:
                numberOfRows = firstSectionArray.count()
            case 1:
                numberOfRows = secondSectionArray.count()
    
            default:
                ()
            }
    
            if numberOfRows == 0 {
                numberOfRows = 1
            }
            return numberOfRows
        }
    

    在cellForRowAtIndexPath中:

        func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
             var numberOfRowsForThisSection = 0
             switch indexPath.section{
             case 0:
                 numberOfRowsForThisSection = firstSectionArray.count()
             case 1:
                 numberOfRowsForThisSection = secondSectionArray.count()
    
             default:
                 ()
             }
             if numberOfRowsForThisSection == 0 {
                 return tableView.dequeueReusableCellWithIdentifier("blankCell") as! UITableViewCell
             }
    
    //        Do the default implementation
    //        .
    //        .
    //        .
    
        }
    

    “哦,不过现在tableView中间多了一个白色的单元格”

    好的,让我们打破它:

        func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
            var numberOfRowsForThisSection = 0
            switch indexPath.section{
            case 0:
                numberOfRowsForThisSection = firstSectionArray.count()
            case 1:
                numberOfRowsForThisSection = secondSectionArray.count()
    
            default:
                ()
            }
            if numberOfRowsForThisSection == 0 {
                return 0.0
            }
        }
    

    【讨论】:

      【解决方案2】:

      ...事实证明我的错误在其他地方。在这种情况下,我不小心尝试删除索引路径 (1, 2147483647)。之所以出现此错误,是因为我假设我用于该部分数据的数组包含我要删除的对象。因为它没有,[array indexOfObject:object] 等于 2147483647。奇怪的是,产生的错误是Invalid number of sections 而不是Invalid number of rows in section

      【讨论】: