iOS - 使用动画展开/折叠UITableView部分

Mik*_*lty 2 iphone animation uitableview ios swift

我想UITableView用动画扩展/折叠我的部分.我使用了这个答案,如果我打电话,它现在有效self.tableView.reloadData().但是我希望当我点击我的自定义UITableView标题时,该部分的单元格应该向下/向上滑动一个漂亮的动画.我试图使用self.tableView.beginUpdates()self.tableView.endUpdates(),但我收到此错误:

Invalid update: invalid number of rows in section 0.  The number of rows contained in an 
existing section after the update (8) must be equal to the number of rows contained in that 
section before the update (0), plus or minus the number of rows inserted or deleted from 
that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out 
of that section (0 moved in, 0 moved out).
Run Code Online (Sandbox Code Playgroud)

这是一些代码.点击该部分时调用的方法:

func expand(sender:UITapGestureRecognizer){

    let tag = (sender.view?.tag)!

    self.tableView.beginUpdates()
    if ausgeklappt[tag] { ausgeklappt[tag] = false }
    else { ausgeklappt[tag] = true }

    self.tableView.endUpdates()
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // Return the number of rows in the section.
    let keyDerSection = sortSpieleDict.keys.array[section]
    let arrayDerSection = sortSpieleDict[keyDerSection]!
    if ausgeklappt[section] == false { return 0 } 
    else { return arrayDerSection.count }
}
Run Code Online (Sandbox Code Playgroud)

谢谢.

Mik*_*lty 10

感谢iOS_DEV,我找到了一个解决方案:只需一行代码即可.我刚刚更换的beginUpdates(),并endUpdates()reloadSections()方法.现在它工作正常!

    func expand(sender:UITapGestureRecognizer){

        let tag = (sender.view?.tag)! // The tag value is the section of my custom UITabelView header view.

        if ausgeklappt[tag] { ausgeklappt[tag] = false }
        else { ausgeklappt[tag] = true }

        // The next line did the trick! 
        self.tableView.reloadSections(NSIndexSet(index: tag), withRowAnimation: UITableViewRowAnimation.Automatic)
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // Return the number of rows in the section.
        let keyDerSection = sortSpieleDict.keys.array[section]
        let arrayDerSection = sortSpieleDict[keyDerSection]!

        if ausgeklappt[section] == false 
        { 
             return 0 
        } 
        else 
        { 
             return arrayDerSection.count 
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 快速注意,你的`if ausgeklappt [tag] ...`反转bool可以写成`ausgeklappt [tag] =!ausgeklappt [tag];`(假设这是一个BOOL数组.) (2认同)