首页 > 解决方案 > 如何为选定的 tableView 行创建自定义图像复选标记附件?

问题描述

如何分配自定义图像以及选择和取消选择.checkmarktableView 附件?

是否也可以将此自定义附件放置在 tableView 行的左侧并在 tableView 中始终可见?

当 tableView 首次加载时,附件仍然显示为取消选择,基本上类似于 Apple 提醒应用程序。

这是我正在寻找的示例:

取消选择:

在此处输入图像描述

已选择:

在此处输入图像描述

目前,这就是我所拥有的:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}

override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    tableView.cellForRow(at: indexPath)?.accessoryType = .none
}

标签: iosswiftuitableview

解决方案


这是一个示例代码。您需要为我的案例创建自己的附件视图我刚刚在自定义视图中添加了一个圆圈。之后您只需将隐藏设置为 true 或 false。

extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 10
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    cell.accessoryView = CheckMarkView.init()
    cell.accessoryView?.isHidden = true
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    //tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
    tableView.cellForRow(at: indexPath)?.accessoryView?.isHidden = false
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    tableView.cellForRow(at: indexPath)?.accessoryView?.isHidden = true
}

}

class CheckMarkView: UIView {
override init(frame: CGRect) {
    super.init(frame: frame) // calls designated initializer
    let img = UIImage(named: "circle.png") //replace with your image name
    let imageView: UIImageView = UIImageView(image: img)
    self.addSubview(imageView)
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}

推荐阅读