如何在 Swift 中重新加载节标题而不使其消失/重新出现?

Pan*_*ngu 2 uitableview ios swift

首先,我要说的是,我UITableViewControllerUITableView.

我的自定义标头类定义如下:

class HeaderCell: UITableViewCell
{
    @IBOutlet var theLabel: UILabel!
    @IBOutlet var theCountLabel: UILabel!

    override func awakeFromNib()
    {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool)
    {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}
Run Code Online (Sandbox Code Playgroud)

我像这样加载自定义标头类:

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
    let headerCell = tableView.dequeueReusableCell(withIdentifier: "HeaderCell") as! HeaderCell

    if section == 0
    {
        headerCell.theLabel.text = "Test 1"
        headerCell.theCountLabel.text = String(myArrayOne.count)
    }
    else if (section == 1)
    {
        headerCell.theLabel.text = "Test 2"
        headerCell.theCountLabel.text = String(myArrayTwo.count)
    }

    return headerCell.contentView
}
Run Code Online (Sandbox Code Playgroud)

每次我从内部删除表视图中的一行时editActionsForRowAt,我都会self.tableView.reloadSections像这样调用:

override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]?
{
    ...

    var indexSet: IndexSet = IndexSet()

    indexSet.insert(indexPath.section)

    if indexPath.section == 0
    {
        self.myArrayOne.remove(at: indexPath.row)
    }
    else if indexPath.section == 1
    {
        self.myArrayTwo.remove(at: indexPath.row)
    }

    self.tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.none)
    self.tableView.reloadSections(indexSet, with: UITableViewRowAnimation.none)

}
Run Code Online (Sandbox Code Playgroud)

现在调用self.tableView.reloadSections确实有效并更新了theCountLabel我的部分标题内的内容。

不过,我已经设定UITableViewRowAnimationnone。但是,当我进一步向下滚动传递UITableView屏幕上当前可见行数并删除一行时,节标题会消失并重新出现并显示更新后的theCountLabel值。

我想始终将我的节标题保持在顶部,即在重新加载该节时不会消失并重新出现。

我还有其他方法可以实现这一目标吗?

谢谢

Pan*_*ngu 5

找到了@Abhinav引用的解决方案:

重新加载表格视图部分,无需滚动或动画

针对Swift 3.0进行了轻微修改:

UIView.performWithoutAnimation {

    self.tableView.beginUpdates()
    self.tableView.reloadSections(indexSet, with: UITableViewRowAnimation.none)
            self.tableView.endUpdates()

}
Run Code Online (Sandbox Code Playgroud)

现在,如果我滚动超过屏幕上可见单元格的数量并删除一行,则headerCell.theCountLabel.text我的节标题中的 会更新,没有任何动画,并保持静止。