ios - Swift tableview 单元格选择以更改复选框图像
问题描述
我正在尝试在 tableview 单元格中实现自定义按钮复选框。当用户单击单元格按钮时,我已经完成了复选框,它可以更改选中和取消选中,但是如果您单击 tableview 单元格,我还需要操作复选框
如果可能的话,请对单选按钮功能提供一些想法,因为我两者都在做。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:MyCustomCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! MyCustomCell
cell.myCellLabel.text = self.animals[indexPath.row]
if selectedRows.contains(indexPath)
{
cell.checkBox.setImage(UIImage(named:"check.png"), for: .normal)
}
else
{
cell.checkBox.setImage(UIImage(named:"uncheck.png"), for: .normal)
}
cell.checkBox.tag = indexPath.row
cell.checkBox.addTarget(self, action: #selector(checkBoxSelection(_:)), for: .touchUpInside)
return cell
}
// method to run when table view cell is tapped
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You tapped cell number \(indexPath.row).")
}
@objc func checkBoxSelection(_ sender:UIButton)
{
let selectedIndexPath = IndexPath(row: sender.tag, section: 0)
if self.selectedRows.contains(selectedIndexPath)
{
self.selectedRows.remove(at: self.selectedRows.index(of: selectedIndexPath)!)
}
else
{
self.selectedRows.append(selectedIndexPath)
}
self.tableView.reloadData()
}
解决方案
您可以在委托中获取选定的单元格并设置复选标记。didSelectRowAt
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) as? MyCustomCell else {
return
}
if self.selectedRows.contains(indexPath) {
self.selectedRows.remove(at: self.selectedRows.index(of: indexPath)!)
cell.checkBox.setImage(UIImage(named:"unccheck.png"), for: .normal)
} else {
self.selectedRows.append(indexPath)
cell.checkBox.setImage(UIImage(named:"check.png"), for: .normal)
}
}
推荐阅读
- java - JavaMail 未正确解码 ISO-8859-1 邮件
- excel - Angular-5:使用 sheetJS 隐藏 excel 文件的网格线并应用单元格样式
- mlr - 是否可以在 mlr 中对分类任务进行子集化,保持正/负类比率不变?
- amcharts - 即使图表出现,amchart 指标加载也不会停止
- excel - Excel中的嵌套If公式
- javascript - 小胡子模板添加条件
- python - 为了通过神经网络运行数据集,我需要做哪些转换?
- c# - 带有 WebApi2 的 Azure AD B2C - 在身份验证后调用 GraphAPI
- python - 访问在 AWS::Lambda::LayerVersion 中定义的自定义 python 模块
- c# - 用逗号插入命令