在UITableViewController中设置默认选定的单元格

Pet*_*Pik 5 uitableview ios swift

我正在尝试设置默认的selectedCell,默认情况下,我的意思是该单元格具有特定的selectedCellBackgroundView.然而即使我已经为它创建了一个方法,它似乎不起作用.它selectedBackgroundView在第一个细胞上没有显示任何内容?我手动选择单元格时工作正常.我究竟做错了什么?

viewDidLoad和viewWillAppear都试过了

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

applySelectionChangesToCell(cell)
Run Code Online (Sandbox Code Playgroud)

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()

}
Run Code Online (Sandbox Code Playgroud)

applySelectionChangesToCell

func applySelectionChangesToCell(cell:UITableViewCell) {

    let backgroundSelectionView = UIView(frame: cell.bounds)
    backgroundSelectionView.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.1)
    cell.selectedBackgroundView = backgroundSelectionView
}
Run Code Online (Sandbox Code Playgroud)

And*_*tta 6

试试这个:

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)
  }
}
Run Code Online (Sandbox Code Playgroud)