How to insert a UITableViewCell at bottom with ani

2019-08-09 23:28发布

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:

enter image description here

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.

2条回答
Summer. ? 凉城
2楼-- · 2019-08-09 23:47

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()
查看更多
女痞
3楼-- · 2019-08-09 23:57

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

enter image description here

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)
}
查看更多
登录 后发表回答