How to remember rows selected and maintain them after reload by default in UITableView?

前端 未结 6 1424
有刺的猬
有刺的猬 2020-12-14 01:09

How can I set a row selected by default? I want to select a row , take the number of selected row with indexpath.row and then reload the table and select the ro

6条回答
  •  一个人的身影
    2020-12-14 01:44

    I realize that this question is rather old (2011), but just to also post an up-to-date answer, in case someone (like me) searches for this problem and stumbles across this question:

    With iOS 9, Apple has improved UITableView a lot. To make sure that focus is not lost when a table is reloaded, just do this:

    tableView.remembersLastFocusedIndexPath = Yes;
    

    and it will "magically work".

    Even better, implement

    - (NSIndexPath *)indexPathForPreferredFocusedViewInTableView:(UITableView *)tableView
    

    in the UITableViewDelegate to let the table know which row you want selected when it is drawn to screen for the very first time.

    Before iOS 9, I'd usually just write my own reloadData method, that gets the currently selected row, reloads the table and then selects it again. Either in the UITableViewController or if I needed that to work with a table where I couldn't prevent code calling reloadData directly, I subclassed UITableView and overrode reloadData (hey, delegation is the preferred way, but sometimes you just have to subclass and override, even in iOS).

提交回复
热议问题