Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView - Multiple and Single selection in different sections

I have a UITableView with 2 different sections. Is it posible to have multiple selection in one section and single selection in the other? If I use:

self.tableView.allowsMultipleSelection = YES;

it affects the whole table.

like image 825
Nahuel Roldan Avatar asked Aug 06 '15 16:08

Nahuel Roldan


1 Answers

I'll expose my own solution, that is pretty much the same one as the one you posted. I think it's a tad better though, since I manually manage the selected rows so I can use the tableView.indexPathsForSelectedRows property later on.

It's written in Swift 2.

Solution

I first declare a NSIndexPath that will store the previously selected item

var indexPathOfPreviouslySelectedRow: NSIndexPath?

I then use these tableView delegate functions (my single selection section is 0, my multiple selection is 1)

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    switch indexPath.section {
    case 0:
        if let previousIndexPath = indexPathOfSelectedRowPaidBy {
            tableView.deselectRowAtIndexPath(previousIndexPath, animated: false)
            tableView.cellForRowAtIndexPath(previousIndexPath)?.accessoryType = UITableViewCellAccessoryType.None
        }
        indexPathOfSelectedRowPaidBy = indexPath
        tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = UITableViewCellAccessoryType.Checkmark

    case 1:
        tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = UITableViewCellAccessoryType.Checkmark

    default:
        break
    }


}

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    switch indexPath.section {
    case 0:
        if let previousIndexPath = indexPathOfSelectedRowPaidBy {
            tableView.deselectRowAtIndexPath(previousIndexPath, animated: false)
            tableView.cellForRowAtIndexPath(previousIndexPath)?.accessoryType = UITableViewCellAccessoryType.None
        }
        indexPathOfSelectedRowPaidBy = nil

    case 1:
        tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = UITableViewCellAccessoryType.None

    default:
        break
    }

}
like image 146
Alexandre G. Avatar answered Nov 12 '22 13:11

Alexandre G.