why reloadData shouldn't be called on methods

2019-08-31 12:05发布

I was trying to implement sparrow like row swiping that shows an action row (My starting point was this code).

for each row I create.. I also create a 'backView' UITableViewCell that references the parent row.. so that when I click delete on the backView for example.. it knows which email to delete etc.

Instead of using iOS's built in editing mode delete.. I just created a button on the backView and attached an event handler to it. the parent cell is the delegate of the back view.. and the back view hands off the delete task to the parent cell.

I followed apple's instruction not to add reloadData in my event handler method. But then things got all messed up.. i'd delete a row and it wouldn't get deleted or gets deleted in the wrong order etc.. I noticed that if i just jumped back to the parent menu after each delete.. things worked perfectly.. and so using this work around (ie brute forcing reloadData in) everything worked perfectly.

My question is (sorry for the long introduction) why are we asked not to use reloadData in insertion/deletion methods? Or is this instruction applicable only when we use the editing mode way of deleting rows? Apple is not quite clear about it.

3条回答
手持菜刀,她持情操
2楼-- · 2019-08-31 12:10

Try this :

  • Tag your delete button with indexPath.row
  • Then in delete button IBAction

assuming you have only one section

-(IBAction)deleteBtn:(id)Sender
{
    UIButton *delBtn = (UIButton *)sender;

    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:delBtn.tag inSection:0]] withRowAnimation:UITableViewRowAnimationLeft];

}

this will only delete the row at indexPath and only reload that row.

查看更多
我命由我不由天
3楼-- · 2019-08-31 12:17

Since - [UITableView reloadData] reloads all the data, it basically invalidates any temporary, non-permanent changes to the UI. You should either reflect these changes in your data structure, or, and I think it's generally a better idea, stick to Apple's default methods (try changing the graphics only, not the logic).

查看更多
爷、活的狠高调
4楼-- · 2019-08-31 12:34

reloadData completly rebuilds table bypassing animations. If you delete or insert rows, use beginUpdates. Here is explanation:

-(void)beginUpdates Begin a series of method calls that insert, delete, or select rows and sections of the receiver. Call this method if you want subsequent insertions, deletion, and selection operations (for example, cellForRowAtIndexPath: and indexPathsForVisibleRows) to be animated simultaneously. This group of methods must conclude with an invocation of endUpdates. These method pairs can be nested. If you do not make the insertion, deletion, and selection calls inside this block, table attributes such as row count might become invalid. You should not call reloadData within the group; if you call this method within the group, you will need to perform any animations yourself.

查看更多
登录 后发表回答