首页 > 解决方案 > 如何将 tableview 部分的选定索引添加到数组

问题描述

我有一个tableViewwithsection headers并且我想将某个用户输入附加到多个 selected headers。我已经创建section headers并能够更改图像section header以显示它已被选中,但我想创建一个array已选中的图像。

这是我的代码section header

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let userModel = Data.userModels[section]
    let cell = tableView.dequeueReusableCell(withIdentifier: "nameCell") as! NameHeaderTableViewCell

    cell.setup(model: userModel)
    cell.checkMarkButton.addTarget(self, action: #selector(handleTap), for: .touchUpInside)
    cell.enable(on: false)
    if isUserEditing == true {
        cell.enable(on: true)
    }
    return cell.contentView
}

这是我section image在用户点击该部分时更改的地方:

    @objc func handleTap(sender: UIButton) {

    sender.isSelected = !sender.isSelected

}

当用户单击 savebutton时,我希望将用户输入附加到选择了的那些单元格中section header。这是该代码:

@IBAction func save(_ sender: Any) {
    //VALIDATION
    guard  mealItemTextField.text != "", let item = mealItemTextField.text else {
        mealItemTextField.placeholder = "please enter an item"
        mealItemTextField.layer.borderWidth = 1
        mealItemTextField.layer.borderColor = UIColor.red.cgColor
        return
    }
    guard  priceTextField.text != "", let price = Double(priceTextField.text!) else {
        priceTextField.placeholder = "please enter a price"
        priceTextField.layer.borderWidth = 1
        priceTextField.layer.borderColor = UIColor.red.cgColor
        return
    }
        tableView.reloadData()
}

目前我被困在如何访问所有被选中indexessections(即具有选中状态的那些)下面是一些截图来帮助可视化程序: 在此处输入图像描述 在此处输入图像描述

PS不确定这是否有帮助,但我使用arrayof填充数据structs。这是该代码:

func numberOfSections(in tableView: UITableView) -> Int {
        return Data.userModels.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if Data.userModels[section].isExpandable {
            return Data.userModels[section].itemModels.count
        } else {
            return 0
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
    if cell == nil {
        cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
    }
    cell?.textLabel?.text = Data.itemModels[indexPath.row].itemName
    return cell!
}

任何帮助表示赞赏,谢谢!

标签: swiftuitableviewuitableviewsectionheader

解决方案


问题是您的复选标记只是标题的视觉特征。当用户点击复选标记时,您只是切换其选定状态:

@objc func handleTap(sender: UIButton) {
    sender.isSelected = !sender.isSelected
}

那是行不通的。您需要在处理节标题的数据模型的一部分中始终跟踪此信息。这样,当单击 Save 按钮时,信息就在数据模型中等待您。您handleTap需要确定这是哪个部分的标题并将信息反映到模型中。数据模型是事实的来源,而不是界面中的某些视图。(我很惊讶当你滚动你的表格视图时你还没有遇到这个问题。)

您的代码的另一个问题是:

let cell = tableView.dequeueReusableCell(withIdentifier: "nameCell") as! NameHeaderTableViewCell

您不能将 UITableViewCell 用作可重用的节标题视图。您需要在这里使用 UITableViewHeaderFooterView 。


推荐阅读