UITableView doesn't keep row selected upon return

后端 未结 7 964
独厮守ぢ
独厮守ぢ 2020-12-17 21:05

i have several table views in my app. I am familiar with the usual behaviour of tables, that when you select a row and progress to a pushed view, it turnes blue, then when y

相关标签:
7条回答
  • 2020-12-17 21:28

    apparently viewWillAppear: of the class UITableView does deselect all cells, even without reloading the cells. The trick described worked for me:

    code from my UITablViewController:

    - (void)viewWillAppear:(BOOL)animated
    {
        NSIndexPath *selectedIndex = [self.tableView indexPathForSelectedRow];
    
        [super viewWillAppear:animated];
    
        //Re select cell
        [self.tableView selectRowAtIndexPath:selectedIndex animated:NO scrollPosition:UITableViewScrollPositionNone];
    };
    
    0 讨论(0)
  • 2020-12-17 21:28
    NSIndexPath *_selectedIndex ;
    

    use the above global variable to store in selected in the table view delegate method

        - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
     _selectedIndex = [self.tableView indexPathForSelectedRow];
    }
    

    and in the following delegate of UINavigationController delegate method

    - (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
    {
    [self.tableView selectRowAtIndexPath:_selectedIndex animated:NO scrollPosition:UITableViewScrollPositionNone];
    
    }
    
    0 讨论(0)
  • 2020-12-17 21:33

    Use this piece of code in the end of didSelectRowAtIndexPath delegate method of table view,

    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    0 讨论(0)
  • 2020-12-17 21:35

    Try

    [tableView deselectRowAtIndexPath:indexPath animated:NO];

    for deselecting a row and

    [tableView selectRowAtIndexPath:indexPath animated:NO];
    

    for highlighting the selected row.

    0 讨论(0)
  • 2020-12-17 21:40

    Its a feature you can turn off.

    In the UITableViewController you can call

    [ self setClearsSelectionOnViewWillAppear:NO ];
    

    This is directly from the file "UITableViewController.h". This feature is documented there.

       @property(nonatomic) BOOL clearsSelectionOnViewWillAppear __OSX_AVAILABLE_STARTING(__MAC_NA, __IPHONE_3_2); 
    // defaults to YES. If YES, any selection is cleared in viewWillAppear:
    
    0 讨论(0)
  • 2020-12-17 21:43

    I am not sure if this is relevant but there is a flag in UITableViewController I just noticed called

    @property(nonatomic) BOOL clearsSelectionOnViewWillAppear NS_AVAILABLE_IOS(3_2); // defaults to YES. If YES, any selection is cleared in viewWillAppear:
    

    I think this should solve some of the problems people are describing here.

    0 讨论(0)
提交回复
热议问题