Created
June 1, 2016 12:14
-
-
Save dede/7ab87a4a0b8d158668d40b9b4e00c2ff to your computer and use it in GitHub Desktop.
Multiple Cell Select - Deselect TableView Example in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| // TableView.swift | |
| // SelectableCell | |
| // | |
| // Created by Samet Dede on 01/06/16. | |
| // Copyright © 2016 Samet DEDE. All rights reserved. | |
| // | |
| import UIKit | |
| class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { | |
| var selectedCells:[Int] = [] | |
| override func viewDidLoad() { | |
| super.viewDidLoad() | |
| // Do any additional setup after loading the view, typically from a nib. | |
| } | |
| override func didReceiveMemoryWarning() { | |
| super.didReceiveMemoryWarning() | |
| // Dispose of any resources that can be recreated. | |
| } | |
| //MARK: TableView | |
| func numberOfSectionsInTableView(tableView: UITableView) -> Int { | |
| return 1 | |
| } | |
| func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
| return 10 | |
| } | |
| func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { | |
| let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) | |
| cell.textLabel?.text = "\(indexPath.row + 1). Cell" | |
| cell.accessoryType = self.selectedCells.contains(indexPath.row) ? .Checkmark : .None | |
| return cell | |
| } | |
| func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { | |
| if self.selectedCells.contains(indexPath.row) { | |
| self.selectedCells.removeAtIndex(self.selectedCells.indexOf(indexPath.row)!) | |
| } else { | |
| self.selectedCells.append(indexPath.row) | |
| } | |
| tableView.reloadData() | |
| } | |
| } | |
//Change background color of cell
var selectedCells:[Int] = []
// cellForRowAt
if self.selectedCells.contains(indexPath.row){
cell.backgroundColor = .red
}else{
cell.backgroundColor = .white
}
// didSelecteRowAt
if self.selectedCells.contains(indexPath.row) {
let myIndex = self.selectedCells.index(of: indexPath.row)
self.selectedCells.remove(at: myIndex!)
} else {
self.selectedCells.append(indexPath.row)
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
old
//self.selectedCells.removeAtIndex(self.selectedCells.indexOf(indexPath.row)!)
//new -> fixed latest
if self.selectedCells.contains(indexPath.row) {
let myIndex = self.selectedCells.index(of: indexPath.row)
self.selectedCells.remove(at: myIndex!)
} else {
self.selectedCells.append(indexPath.row)
}