首页 > 解决方案 > IOS swift 4展开和折叠表格视图不起作用并导致崩溃

问题描述

以下是我添加部分标题视图单元格的代码

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let cell = tableView.dequeueReusableCell(withIdentifier: "menuHeaderTableViewCellID") as! MenuHeaderTableViewCell
    cell.foodMenuItems = menuResult?.foodMenuItems?[section]
    cell.setParentUI()
    cell.expandCollapseClicked = {
        [weak self]
        (postiton) in
        let isCollapsed = self?.menuResult?.foodMenuItems?[postiton].isCollapsed ?? false
        self?.menuResult?.foodMenuItems?[postiton].isCollapsed = !isCollapsed
        self?.tableViewMenu?.beginUpdates()
        self?.tableViewMenu?.reloadSections([section], with: .fade)
        self?.tableViewMenu?.endUpdates()

    }
    return cell
}

以下是每行和部分中的计数代码

 func numberOfSections(in tableView: UITableView) -> Int {
    return (menuResult?.foodMenuItems?.count) ?? 0
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let rowCount = menuResult?.foodMenuItems?[section].items?.count ?? 0
    let isCollpased = menuResult?.foodMenuItems?[section].isCollapsed ?? false
    return isCollpased ? 0 : rowCount
}

以下是标题视图单元格内的代码

@IBAction func expandCollapseClicked(_ sender: UIButton) {
    guard let superView = self.superview as? UITableView else {
        return
    }
    expandCollapseClicked?(superView.indexPath(for: self)?.section ?? 0)
}

我在折叠第一部分时遇到问题,我的标题消失了,当我尝试折叠其他部分时出现以下异常如何解决这个问题?

 *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (0) must be equal to the number of rows contained in that section before the update (25), 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).'
 *** First throw call stack:

标签: iosswiftuitableview

解决方案


问题可能在:

  1. 避免dequeueReusableCell。尝试使用带有标签和按钮的 UIView。
  2. expandCollapseClicked = {...} 应该由 UIButton 调用。因为它的发送者是 UIButton。尝试使用:

    view.button.expandCollapseClicked = {...}

希望这会奏效。


推荐阅读