user11349745
user11349745

Reputation:

How to create custom image check mark accessory for selected tableView rows?

How can I assign a custom image and for the select and deselect .checkmark tableView accessory?

Is it possible to also position this custom accessory on the left side of the tableView row and have constantly visible in the tableView?

When the tableView first loads the accessory is still shown just deselected essentially similar to the Apple Reminders app.

Here is an example of what I am looking for:

Deselected:

enter image description here

Selected:

enter image description here

Currently, this is what I have:

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
}

Upvotes: 0

Views: 749

Answers (1)

Muhammad Shauket
Muhammad Shauket

Reputation: 2778

Here is a sample code. You need to create your own accessory view for my case I Just added one circle inside a custom view.After that you just need to make hidden true or 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")
}
}

Upvotes: 1

Related Questions