Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to select Table View row selection with custom checkbox button?

How to select tableview row with custom button . i have another button called select all its outside of the table view my question is while clicking outside of the tableview button how to select and deselect inside tableview rows? At the same time i could able to select single row in the tableview ? how to do it in swift 3? This is my code in cellforrow method

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


    let identifier = "Custom"
    var cell: TStudentAttendanceCell! = tableView.dequeueReusableCell(withIdentifier: identifier) as? TStudentAttendanceCell
    if cell == nil {
        tableView.register(UINib(nibName: "TStudentAttendanceCell", bundle: nil), forCellReuseIdentifier: identifier)
        cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? TStudentAttendanceCell
    }
    print("studentAttendanvceArray--",studentAttendanceArray.object(at: indexPath.row) )
    var localDic :NSDictionary!

    localDic = studentAttendanceArray.object(at: indexPath.row) as! NSDictionary

    Common.sharedInstance.StopActivity()        
    cell.profile_img.image = self.image
    cell.name_lbl.text = localDic["student_name"] as? String
    cell.selectionStyle = UITableViewCellSelectionStyle.none
    cell.contentView.backgroundColor = UIColor.clear
    let whiteRoundedView : UIView = UIView(frame: CGRect(x: 10, y: 8, width: self.view.frame.size.width - 20, height: 90))

    whiteRoundedView.layer.backgroundColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [1.0, 1.0, 1.0, 0.9])
    whiteRoundedView.layer.masksToBounds = false
    whiteRoundedView.layer.cornerRadius = 2.0
    whiteRoundedView.layer.shadowOffset = CGSize(width: -1, height: 1)
    whiteRoundedView.layer.shadowOpacity = 0.2
    cell.contentView.addSubview(whiteRoundedView)
    cell.contentView.sendSubview(toBack: whiteRoundedView)

    return cell

}
like image 809
Ram Avatar asked Nov 15 '17 06:11

Ram


People also ask

How do you get the IndexPath row when a button in a cell is tapped?

add an 'indexPath` property to the custom table cell. initialize it in cellForRowAtIndexPath. move the tap handler from the view controller to the cell implementation. use the delegation pattern to notify the view controller about the tap event, passing the index path.

What is Tableview delegate?

Methods for managing selections, configuring section headers and footers, deleting and reordering cells, and performing other actions in a table view.

What is Uitableview in Swift?

A view that presents data using rows in a single column. iOS 2.0+ iPadOS 2.0+ Mac Catalyst 13.1+ tvOS 9.0+


2 Answers

enter image description here

ViewController

class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {

  @IBOutlet var tableView: UITableView!
  var allStudentsArr:[[String:String]] = []
  var selectedRows:[IndexPath] = []


  override func viewDidLoad() {
    super.viewDidLoad()
    tableView.allowsSelection = false
    allStudentsArr = [["name":"name1"],["name":"name2"],["name":"name3"],["name":"name4"],["name":"name5"],["name":"name6"],["name":"name7"],["name":"name8"]]
  }
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return allStudentsArr.count
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! CustomTableViewCell
    cell.nameLbl.text = allStudentsArr[indexPath.row]["name"]
    if selectedRows.contains(indexPath)
    {
      cell.checkBox.setImage(UIImage(named:"selected"), for: .normal)
    }
    else
    {
      cell.checkBox.setImage(UIImage(named:"unselected"), for: .normal)
    }
    cell.checkBox.tag = indexPath.row
    cell.checkBox.addTarget(self, action: #selector(checkBoxSelection(_:)), for: .touchUpInside)
    return cell
  }
  @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()
  }
  @IBAction func selectAllBtnAction(_ sender: UIBarButtonItem) {
    self.selectedRows = getAllIndexPaths()
    self.tableView.reloadData()
  }

  func getAllIndexPaths() -> [IndexPath] {
    var indexPaths: [IndexPath] = []
      for j in 0..<tableView.numberOfRows(inSection: 0) {
        indexPaths.append(IndexPath(row: j, section: 0))
      }
        return indexPaths
  }
}

Custom Cell

class CustomTableViewCell: UITableViewCell {

  @IBOutlet var nameLbl: UILabel!
  @IBOutlet var checkBox: UIButton!
}
like image 196
RajeshKumar R Avatar answered Oct 03 '22 00:10

RajeshKumar R


Thats how you can programatically select all rows of a single section

@IBAction func didTapSelectAllButton(sender: UIButton) {
        let totalRows = tableView.numberOfRows(inSection: 0)// Make some logic if you have more than 1 section
        for row in 0..<totalRows {
            let indexPath = IndexPath(row: row, section: 0)
            tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
        }
    }

If you don't want to use default check box of tableView then disable multipleSelection from tableView and implement logic using an extra global array.

var selectedArrayIndex = [Int]()
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if selectedArrayIndex.contains(indexPath.row) {
        selectedArrayIndex.remove(at: selectedArrayIndex.index(of: indexPath.row)!)
    }else {
        selectedArrayIndex.append(indexPath.row)
    }
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if selectedArrayIndex.contains(indexPath.row) {
        // Enable You Check
        cell.checkBoxView.isHidden = false
    }else {
        cell.checkBoxView.isHidden = true
    }
}
@IBAction func didTapSelectAllButton(sender: UIButton) {
    let totalRows = tableView.numberOfRows(inSection: 0)// Make some logic if you have more than 1 section
    selectedArrayIndex.removeAll()
    for row in 0..<totalRows {
        selectedArrayIndex.append(row)
    }
}
like image 34
Syed Qamar Abbas Avatar answered Oct 02 '22 23:10

Syed Qamar Abbas