2015-11-11 3 views
3

Я пытаюсь установить выбранный по умолчанию Cell, и по умолчанию я имею в виду, что ячейка имеет конкретный selectedCellBackgroundView. Однако, несмотря на то, что я создал метод для него, он, похоже, не работает. Он не показывает selectedBackgroundView на первой ячейке? Он отлично работает, когда я выбираю ячейку вручную. Что я делаю не так?Установить ячейку по умолчанию, выбранную в UITableViewController

viewDidLoad и viewWillAppear пытался как

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 
} 
+1

Думаю, вам действительно нужно выбрать ячейку. –

+0

http://stackoverflow.com/a/13808981/312594 – par

+0

Я попытался выбрать его так же, как и без результата 'tableView! .selectRowAtIndexPath (indexPath, animated: true, scrollPosition: UITableViewScrollPosition.None)' –

ответ

5

попробуйте следующее:

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) 
    } 
} 
Смежные вопросы