How to insert a UITableViewCell at bottom with animation?

馋奶兔 提交于 2019-12-11 12:46:42

问题


I have read https://stackoverflow.com/questions/

and tried as this:

//UITableView 
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 50;

//Update the full code for the "return" key action
- (void)inputViewDidTapReturn:(MyInputView *)inputView text:(NSString *)text{
    NSLog(@"send text-----%@",text);
    [self.messageManager sendMessageTo:self.sessionID message:text  completion:^(BOOL success, Message *message) {
        if (success) {

            [self.dataArray addObject:message];

            NSIndexPath * bottomIndexPath = [NSIndexPath indexPathForRow:self.dataArray.count-1 inSection:0];

            [self.tableView beginUpdates];
            [self.tableView insertRowsAtIndexPaths:@[bottomIndexPath] withRowAnimation:UITableViewRowAnimationLeft];
            [self.tableView endUpdates];


            [self.tableView scrollToRowAtIndexPath:bottomIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];

        } else {
        }
    }];
}

But the result did not show correctly:

It started scroll from the bottom of the screen.

The UITableView and UITableViewCell are both used Auto Layout and the UITableView is on top of the keyboard already.

Any help will be greatly appreciated.


回答1:


Try this.

Objective C

[self.dataArray addObject:message];
[self.tableView reloadData];

dispatch_async(dispatch_get_main_queue(), ^{
    NSIndexPath *bottomIndexPath = [NSIndexPath indexPathForRow:self.dataArray.count-1 inSection:0];
    [self.tableView scrollToRowAtIndexPath:bottomIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
});

Output

Swift

self.dataArray.add(messasge)
self.tableView.reloadData()

DispatchQueue.main.async {
    let bottomIndexPath = IndexPath(row: self.dataArray.count-1, section: 0)
    self.tableView.scrollToRow(at: bottomIndexPath, at: .bottom, animated: true)
}



回答2:


The correct way is to use beginUpdates and endUpdates methods to insert cell into table view. First you should add the item into your array.

array.append(item)

This will not update the table view yet, only the array, to add the cell into the view just call

tableView.beginUpdates()
tableView.insertRows(at: [IndexPath(row: array.count-1, section: 0)], with: .automatic)
tableView.endUpdates()


来源:https://stackoverflow.com/questions/52148205/how-to-insert-a-uitableviewcell-at-bottom-with-animation

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