swift - 如何将 tableview 部分的选定索引添加到数组
问题描述
我有一个tableView
withsection 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()
}
目前我被困在如何访问所有被选中indexes
的sections
(即具有选中状态的那些)下面是一些截图来帮助可视化程序:
PS不确定这是否有帮助,但我使用array
of填充数据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!
}
任何帮助表示赞赏,谢谢!
解决方案
问题是您的复选标记只是标题的视觉特征。当用户点击复选标记时,您只是切换其选定状态:
@objc func handleTap(sender: UIButton) {
sender.isSelected = !sender.isSelected
}
那是行不通的。您需要在处理节标题的数据模型的一部分中始终跟踪此信息。这样,当单击 Save 按钮时,信息就在数据模型中等待您。您handleTap
需要确定这是哪个部分的标题并将信息反映到模型中。数据模型是事实的来源,而不是界面中的某些视图。(我很惊讶当你滚动你的表格视图时你还没有遇到这个问题。)
您的代码的另一个问题是:
let cell = tableView.dequeueReusableCell(withIdentifier: "nameCell") as! NameHeaderTableViewCell
您不能将 UITableViewCell 用作可重用的节标题视图。您需要在这里使用 UITableViewHeaderFooterView 。
推荐阅读
- mongodb - 聚合,从 2 个集合中查找并提取结果
- algorithm - 检查矩阵中元素邻居的最佳方法
- ruby-on-rails - 如何在 Rails 中使用 after_create 回调方法?
- javascript - 如果密钥存在如何更新 - 续集
- java - 流利的等待不能在硒中工作以获取角度
- android - 使用渐进式 Web 应用程序时 Android 软菜单重叠
- ios - 如何在Swift中点击可扩展表格单元格时自动隐藏键盘
- java - Spring WebSocket convertAndSendToUser 到特定的 sessionID
- msys - 如何使用 make 命令(MSYS)来构建 DCMTK?
- javascript - 当使用切片调用函数时,javascript获取指定数量的数组