Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save leoiphonedev/ed9e2ee8720bef8fc92be90de3c01962 to your computer and use it in GitHub Desktop.
Save leoiphonedev/ed9e2ee8720bef8fc92be90de3c01962 to your computer and use it in GitHub Desktop.
How to maintain checkbox state when scrolling uitableview
//
// ViewController.swift
// addCheckBoxonTable-Tutorial
//
// Created by Aman Aggarwal on 2/1/18.
// Copyright © 2018 iostutorialjunction.com. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource {
@IBOutlet weak var tblList: UITableView!
var selectedRows = [IndexPath]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tblList.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CheckBoxCell")
if let lbl = cell?.contentView.viewWithTag(1) as? UILabel {
lbl.text = "item-\(1)"
}
if let btnChk = cell?.contentView.viewWithTag(2) as? UIButton {
btnChk.addTarget(self, action: #selector(checkboxClicked(_ :)), for: .touchUpInside)
btnChk.isSelected = false
if selectedRows.contains(indexPath) {
btnChk.isSelected = true
}
}
return cell!
}
@objc func checkboxClicked(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
let point = sender.convert(CGPoint.zero, to: tblList)
let indxPath = tblList.indexPathForRow(at: point)
if selectedRows.contains(indxPath) {
selectedRows.remove(at: selectedRows.index(of: indxPath)!)
} else {
selectedRows.append(indxPath)
}
tblList.reloadRows(at: [indxPath], with: .automatic)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
@mawaddat
Copy link

Hi, I have exactly follow your code. But when I scroll up after selecting any checkbox its automatically unchecked and any random check box is selected. Could you please explain this behaviour ?

@leoiphonedev
Copy link
Author

leoiphonedev commented Feb 20, 2022 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment