Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save leoiphonedev/ed9e2ee8720bef8fc92be90de3c01962 to your computer and use it in GitHub Desktop.

Select an option

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.
}
}
@tqi-mcamargos

Copy link
Copy Markdown

hi.

could you give me the whole project, please?

@leoiphonedev

Copy link
Copy Markdown
Author

hi.

could you give me the whole project, please?

Please check this link https://iostutorialjunction.com/2018/02/add-custom-checkbox-on-uitableviewcell.html

@mawaddat

Copy link
Copy Markdown

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

leoiphonedev commented Feb 20, 2022 via email

Copy link
Copy Markdown
Author

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