Peter Pik
Peter Pik

Reputation: 11193

Set the selected Cell without pushing to new viewController

I've created below code in order to change the textColor when selecting and deselecting a cell. However the issue is when the view is loaded all of the titleLabels is grey and i want the first cell to be selected. However i can't seem find out how to? i've tried just to set the first cell to another color however when i then select another cell it is not changing to grey. How can i achieve this?

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

     var cell = tableView.cellForRowAtIndexPath(indexPath) as! MenuViewCell

        cell.titleLabel?.textColor = UIColor(rgba: "#E91E63")

}


override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {

        var cell = tableView.cellForRowAtIndexPath(indexPath) as! MenuViewCell
        cell.titleLabel?.textColor = UIColor.whiteColor()

}

Upvotes: 0

Views: 43

Answers (2)

Bhushan B
Bhushan B

Reputation: 2510

You can create another function and write the changes you want to do in didSelectRowAtIndexPath method. For ex.

func applySelectionChangesToCell(cell:UITableViewCell) {
     cell.textLabel?.textColor = UIColor.redColor()
}

Now you can call this function from didSelectRowAtIndexPath method and in viewDidAppear/after table reloads.

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
     var cell = tableView.cellForRowAtIndexPath(indexPath)
     applySelectionChangesToCell(cell!)
}

and

override func viewDidAppear(animated: Bool) {
     super.viewDidAppear(animated)
     let indexPath = NSIndexPath(forRow: 0, inSection: 0)
     let cell = self.tableView.cellForRowAtIndexPath(indexPath)

     if let cell = cell {
          self.tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: UITableViewScrollPosition.None)
          applySelectionChangesToCell(cell)
     }
}

Upvotes: 1

Lucho
Lucho

Reputation: 1044

to select the first cell you, assuming that exist at least a cell

 override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    let indexPath = NSIndexPath(forRow: 0, inSection: 0)
    self.tableView.cellForRowAtIndexPath(indexPath)?.setSelected(true, animated: true)
}

Upvotes: 0

Related Questions