Why can't I call reloadData AND deselectRowAtIndexPath in viewWillAppear:animated at the same time?

有些话、适合烂在心里 提交于 2019-12-21 02:55:16

问题


I have a UITableView with cells that push viewControllers onto the stack when selected. The child viewControllers take user input and then pops off the stack.

When the child viewController is popped, I want the parent tableView to update the value of the selected cell AND then deselect the row. I can update the cell using reloadData, and I can deselect the row using deselectRowAtIndexPath - but I can't do both at the same time.

I understand why this is - reloadData deselects the cell implicitly, and deselectRowAtIndexPath deselects it explicitly, but I find it curious that I can't find anyone wanting to achieve the same reload/deselect behavior. What am I missing here?

All code is in viewWillAppear:animated - I can get close if I put deselectRowAtIndexPath in viewWillAppear and reloadData in viewDidAppear, but this isn't what I want.


回答1:


When you reload a cell, it automatically gets deselected. That's because you don't set a cell's selected property to YES in tableView:cellForRowAtIndexPath:. So you will have to deal with this differently. Either identify that the cell at indexPath needs to be selected and appropriately set its selected property to YES in tableView:cellForRowAtIndexPath: or select it after you reload the data. In such case, you can execute the following methods –

[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                      withRowAnimation:UITableViewRowAnimationNone];

[self.tableView selectRowAtIndexPath:indexPath 
                            animated:NO
                      scrollPosition:UITableViewScrollPositionNone];

[self.tableView deselectRowAtIndexPath:indexPath animated:YES];

The order of steps are :-

  1. Reload the row without any animation.
  2. Select the row without animation.
  3. Deselect the row with animation.

This way I think you can get the effect you want.




回答2:


When the user taps the row the first time to load the editable view controller deselect the UITableViewCell before loading the editable ViewController.



来源:https://stackoverflow.com/questions/6462393/why-cant-i-call-reloaddata-and-deselectrowatindexpath-in-viewwillappearanimate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!