UITableViewCell doesn't get deselected when swiping back quickly

后端 未结 16 1395
甜味超标
甜味超标 2021-01-29 23:49

I\'ve now updated three of my apps to iOS 7, but in all three, despite them not sharing any code, I have the problem where if the user swipes to go back in the navigation contro

16条回答
  •  暖寄归人
    2021-01-30 00:36

    Fabio's answer works well but doesn't give the right look if the user swipes just a little bit and then changes their mind. In order to get that case right you need to save the selected index path and reset it when necessary.

    - (void)viewDidAppear:(BOOL)animated
    {
        [super viewDidAppear:animated];
        self.savedSelectedIndexPath = nil;
    }
    
    - (void)viewWillDisappear:(BOOL)animated
    {
        [super viewWillDisappear:animated];
        if (self.savedSelectedIndexPath) {
            [self.tableView selectRowAtIndexPath:self.savedSelectedIndexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
        }
    }
    
    - (void)viewWillAppear:(BOOL)animated
    {
        [super viewWillAppear:animated];
        self.savedSelectedIndexPath = self.tableView.indexPathForSelectedRow;
    
        if (self.savedSelectedIndexPath) {
            [self.tableView deselectRowAtIndexPath:self.savedSelectedIndexPath animated:YES];
        }
    }
    

    If using a UITableViewController, make sure to disable the built-in clearing:

    self.clearsSelectionOnViewWillAppear = NO;
    

    and add the property for savedSelectedIndexPath:

    @property(strong, nonatomic) NSIndexPath *savedSelectedIndexPath;
    

    If you need to do this in a few different classes it might make sense to split it out in a helper, for example like I did in this gist: https://gist.github.com/rhult/46ee6c4e8a862a8e66d4

提交回复
热议问题