Tom Tom - 4 months ago 11
Swift Question

Function does not work correctly until after a row has been selected

I have a tableview inside a viewcontroller. I have a little function to select all rows in the tableview. When I first display the viewcontroller and hit the select all button the function does not work. However, if I firstly select a row and then press the select all button, the function works as it should and all rows are selected. I'm not sure why this is happening. The tableview's delegate and data source have been set up in the storyboard.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:myTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! myTableViewCell

cell.accessoryType = .None

if allJobsSelected {

let bgColorView = UIView()
bgColorView.backgroundColor = UIColor(red: 250/255, green: 182/255, blue: 17/255, alpha: 1)
cell.contentView.backgroundColor = UIColor(red: 250/255, green: 182/255, blue: 17/255, alpha: 1)
cell.selectedBackgroundView = bgColorView
cell.accessoryType = .Checkmark
cell.highlighted = false

cell.selected = true
// cell.accessoryType = .Checkmark
self.tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: UITableViewScrollPosition.None)
self.tableView(self.tableView, didSelectRowAtIndexPath: indexPath)

}

var job: Jobs!

job = jobs[UInt(indexPath.row)] as! Jobs

cell.reports2JobTitle.text = job.jobTitle


return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

self.tableView.allowsMultipleSelection = true

if let cell:myTableViewCell = tableView.cellForRowAtIndexPath(indexPath) as? myTableViewCell {

let bgColorView = UIView()
bgColorView.backgroundColor = UIColor(red: 250/255, green: 182/255, blue: 17/255, alpha: 1)
cell.contentView.backgroundColor = UIColor(red: 250/255, green: 182/255, blue: 17/255, alpha: 1)
cell.selectedBackgroundView = bgColorView
cell.accessoryType = .Checkmark
cell.highlighted = false
self.tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: UITableViewScrollPosition.Bottom)

}


}

@IBAction func doSelectAll(sender: UIBarButtonItem) {
let totalRows = tableView.numberOfRowsInSection(0)
for row in 0..<totalRows {
tableView.selectRowAtIndexPath(NSIndexPath(forRow: row, inSection: 0), animated: false, scrollPosition: UITableViewScrollPosition.None)
}
}

Answer

It would probably be a good idea to move this line:

self.tableView.allowsMultipleSelection = true

to your viewDidLoad

You are not guaranteed that the didSelect is called immediately -- it might be that each select is turning off the previous one and then a single didSelect is being called on the last row.

Comments