iphaaw
iphaaw

Reputation: 7204

Swift : Single Selection with UITableViews

I have a regular UITableView with single selection enabled. My problem is that if the user selects multiple rows then the original rows remain selected. I also have a problem where the highlight remains gray no matter if I set the cell.selectionStyle = UITableViewCellSelectionStyle.Blue

My view controller is defined in the Storyboard.

Table View

Table Cell View

Here are some screenshots:

selection 1 selection 2

Here is my code:

class AreaViewController: UITableViewController
{

    override func viewDidLoad()
    {
        super.viewDidLoad()
        self.tableView.backgroundColor = backgroundColour
    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCellWithIdentifier("areacell", forIndexPath: indexPath) as! UITableViewCell
        cell.selectionStyle = UITableViewCellSelectionStyle.Blue

        cell.textLabel?.text = "Cell Contents"
        cell.textLabel?.textColor = UIColor.whiteColor()

        return cell
    }

     override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) 
    {
         let cell = tableView.dequeueReusableCellWithIdentifier("areacell", forIndexPath: indexPath) as! UITableViewCell

    }
}

I must be missing something obvious but I've not been able to see anything non standard.

Upvotes: 1

Views: 1617

Answers (2)

iphaaw
iphaaw

Reputation: 7204

Argh! I found it at last. Seems like I was calling let cell = tableView.dequeueReusableCellWithIdentifier("areacell", forIndexPath: indexPath) as! UITableViewCell in the didSelectRowAtIndexPath method. Removing it caused everything to start working again. Obvious really. Thanks for your help zisoft in putting me on the right road.

Upvotes: 0

zisoft
zisoft

Reputation: 23078

From the UITableViewCell Class Reference

UITableViewCellSelectionStyleBlue The cell has a default background color when selected.

In iOS 7, the selection color is no longer blue. Use UITableViewCellSelectionStyleDefault instead.

If you want a special background color for selected cells you have to set the cells' backgroundView:

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

    // Configure the cell...
    let backgroundView = UIView()
    backgroundView.backgroundColor = UIColor.redColor()
    cell.selectedBackgroundView = backgroundView

    return cell
}

Looks like this:

enter image description here

Upvotes: 1

Related Questions