首页 > 解决方案 > 如何通过 numberOfRowInSection 函数联系发件人?

问题描述

我想用标题制作可扩展的表格视图单元格。我有我的数据模型。我为确定的单元格情况添加了 isExpanded 变量 bool,因此在 numberOfRowsInSection 函数中给了我索引错误。我有具有 isExpanded 变量的逻辑,但它不能正常工作。我该如何解决?这是我的代码:

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
        if self.userAdressDict[0].isExpanded == true {
            return 0
        }
        if self.userAdressDict[0].isExpanded == false {
            return self.userAdressDict.count
        }
    }
    if section == 1 {
        return self.userAdressDictForTeslim.count

    }
    return 1
}

这是我的标题视图代码:

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    if section == 0 {
        let button = UIButton(type: .system)
        button.setTitle("Kapat", for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.backgroundColor = .lightGray
        button.titleLabel!.font = UIFont.boldSystemFont(ofSize: 14)
        button.addTarget(self, action: #selector(handleExpandCloseForAlim(sender:)), for: .touchUpInside)
        return button
    }
    if section == 1 {
        let button = UIButton(type: .system)
        button.setTitle("Kapat", for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.backgroundColor = .lightGray
        button.titleLabel!.font = UIFont.boldSystemFont(ofSize: 14)
        button.addTarget(self, action: #selector(handleExpandCloseForTeslim), for: .touchUpInside)
        return button
    }
    else{
        return nil
    }
}

而这里的按钮动作功能:

@objc func handleExpandCloseForAlim(sender: UIButton) {
    var indexPaths = [IndexPath]()
    for row in self.userAdressDict.indices{
        print(0 , row)
        let indexPath = IndexPath(row: row, section: 0)
        indexPaths.append(indexPath)
    }
    let indexPath = IndexPath(row: (sender.tag), section: 0)
    let adresso = self.userAdressDict[indexPath.row]
    if adresso.isExpanded == true {
        tableView.deleteRows(at: indexPaths , with: .fade)
    }
    if adresso.isExpanded == false {
        tableView.insertRows(at: indexPaths, with: .fade)
    }
    //self.userAdressDict.removeAll()

}

我可以使用 removeAll() 代码进行删除过程。但我也想插入行,所以这种方式不是正确的方法。(userAdressDict 是我保存数据的模型)。在handleExpandCloseForAlim 函数的发送者到达isExpanded 变量。最后我对 numberOfRowsInSection 部分有疑问。

标签: iosswift

解决方案


更改这些行

if self.userAdressDict[0].isExpanded == false {
            return self.userAdressDict.count
        }
    }
    if section == 1 {
        return self.userAdressDictForTeslim.count

    }

if self.userAdressDict[0].isExpanded == false {
            return self.userAdressDict.count - 1
        }
    }
    if section == 1 {
        return self.userAdressDictForTeslim.count - 1

    }

推荐阅读