Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default selected cell in UITableViewController

I'm trying to set a default selectedCell and by default i mean that the cell has a specific selectedCellBackgroundView. However even though i've created a method for it, it does not seem to work. It does not show any selectedBackgroundView on the first cell? It works fine when i select a cell manually. What am i doing wrong?

viewDidLoad and viewWillAppear tried both

let indexPath = NSIndexPath(forRow: 0, inSection: 0)
let cell = tableView!.cellForRowAtIndexPath(indexPath)! as UITableViewCell

applySelectionChangesToCell(cell)

didSelectRowAtIndexPath

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

    let cell = tableView.cellForRowAtIndexPath(indexPath)! as UITableViewCell
    applySelectionChangesToCell(cell)

    NSUserDefaults.standardUserDefaults().setInteger(menuArray[indexPath.row].id!, forKey: "leagueId")

    self.sideMenuViewController.hideMenuViewController()

}

applySelectionChangesToCell

func applySelectionChangesToCell(cell:UITableViewCell) {

    let backgroundSelectionView = UIView(frame: cell.bounds)
    backgroundSelectionView.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.1)
    cell.selectedBackgroundView = backgroundSelectionView
}
like image 589
Peter Pik Avatar asked Nov 11 '15 19:11

Peter Pik


People also ask

How do you create a table view cell subclass?

The same way that you create a UIViewController or UITableViewController : In your project, go to New File. Select Cocoa Touch Class under iOS. The subclass is UITableViewCell and the name is whatever name you're giving it. Within that class, you drag your buttons, labels, etc to create your outlets.


1 Answers

try this:

class TableViewController: UITableViewController {
  override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 5
  }

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

    // setup selectedBackgroundView
    let backgroundSelectionView = UIView()
    backgroundSelectionView.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.1)
    cell.selectedBackgroundView = backgroundSelectionView

    return cell
  }

  override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    let indexPath = NSIndexPath(forRow: 0, inSection: 0)
    tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: .None)
  }
}
like image 82
André Slotta Avatar answered Sep 28 '22 03:09

André Slotta