Quick cell selection in each section
I have a little problem when selecting multiple cells in swift.
I don't want the user to select as many cells as they want, they are only allowed to select three cells (one in each section). To make it clearer, I'll give you the code.
I have three sections:
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 3
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerCell = tableView.dequeueReusableCellWithIdentifier("HeaderCell") as! CustomHeaderCell
/* let headerCell = tableView.dequeueReusableCellWithIdentifier("HeaderCell") as CustomHeaderCell */
// headerCell.backgroundColor = UIColor.set(#E6E2E1)
switch (section) {
case 0:
headerCell.headerLabel.text = "Bundesliga";
//return sectionHeaderView
case 1:
headerCell.headerLabel.text = "BBVA";
//return sectionHeaderView
case 2:
headerCell.headerLabel.text = "BPL";
//return sectionHeaderView
default:
headerCell.headerLabel.text = "Other";
}
return headerCell
}
And I want the user to give for example 5 Club
to select from each League
. He must choose his favorite Club
in each League
. I don't want to do something like this:
tableView.allowsMultipleSelection = true
Because I want to only allow one choice per section. How can I restrict the user this way?
+3
source to share
1 answer
This should work for you:
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
let selectedIndexPaths = indexPathsForSelectedRowsInSection(indexPath.section)
if selectedIndexPaths?.count == 1 {
tableView.deselectRowAtIndexPath(selectedIndexPaths!.first!, animated: true)
}
return indexPath
}
func indexPathsForSelectedRowsInSection(section: Int) -> [NSIndexPath]? {
return (tableView.indexPathsForSelectedRows() as? [NSIndexPath])?.filter({ (indexPath) -> Bool in
indexPath.section == section
})
}
+5
source to share