gpt4 book ai didi

ios - Swift 表格 View 单元格选择更改复选框图像

转载 作者:行者123 更新时间:2023-11-30 11:08:56 27 4
gpt4 key购买 nike

我正在尝试在表格 View 单元格中实现自定义按钮复选框。我已经完成了复选框,当用户单击单元格按钮时,它可以更改选中和取消选中,但如果您单击表格 View 单元格,我也需要操作该复选框

如果可能,请提供有关单选按钮功能的一些想法,因为我正在做这两件事。

   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 委托(delegate)中获取所选单元格并设置复选标记。

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)
}
}

关于ios - Swift 表格 View 单元格选择更改复选框图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52392711/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com