问题
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