我想用标题制作可扩展的tableview单元。我有我的数据模型。我为确定的单元格情况添加了isExpanded变量bool,所以在numberOfRowsInSection函数中给了我Index错误。我有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部分的问题。
最佳答案
使用guard来查看数组中是否有任何元素,例如:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
guard let element = self.userAdressDict.first as? AdresStruct else { return 0 }
if element.isExpanded {
return 0
}
else {
return self.userAdressDict.count
}
}
if section == 1 {
return self.userAdressDictForTeslim.count
}
return 1
}
关于ios - 如何通过numberOfRowInSection函数到达发件人?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58415045/