gpt4 book ai didi

ios - 在底部添加单元格并滚动 UITableView

转载 作者:搜寻专家 更新时间:2023-10-30 20:15:22 25 4
gpt4 key购买 nike

我想在 UITableView 的底部添加单元格,然后滚动以使其完全可见(就像在 Whatsapp 中发送或接收消息时一样)。

我试过这样做:

[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:[self.tableView numberOfRowsInSection:0]-1 inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];

但这会造成图形故障,表格会闪烁,滚动效果不佳而不是流畅。

有什么帮助吗?

最佳答案

这里我所做的是,插入一行,然后更改 tableView 的内容插图

-(IBOutlet)sendButton:(id)sender
{
[array addObject:textView.text];
[self addAnotherRow];
}
- (void)addAnotherRow {
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:(array.count - 1) inSection:0];
[self.messagesTableView beginUpdates];
[self.messagesTableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[self.messagesTableView endUpdates];
[self updateContentInsetForTableView:self.messagesTableView animated:YES];

// TODO: if the scroll offset was at the bottom it can be scrolled down (allow user to scroll up and not override them)

[self.messagesTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

- (void)updateContentInsetForTableView:(UITableView *)tableView animated:(BOOL)animated {
NSUInteger lastRow = [self tableView:tableView numberOfRowsInSection:0];
NSLog(@"last row: %lu", (unsigned long)lastRow);
NSLog(@"items count: %lu", (unsigned long)array.count);

NSUInteger lastIndex = lastRow > 0 ? lastRow - 1 : 0;

NSIndexPath *lastIndexPath = [NSIndexPath indexPathForItem:lastIndex inSection:0];
CGRect lastCellFrame = [self.messagesTableView rectForRowAtIndexPath:lastIndexPath];

// top inset = table view height - top position of last cell - last cell height
CGFloat topInset = MAX(CGRectGetHeight(self.messagesTableView.frame) - lastCellFrame.origin.y - CGRectGetHeight(lastCellFrame), 0);

// What about this way? (Did not work when tested)
// CGFloat topInset = MAX(CGRectGetHeight(self.tableView.frame) - self.tableView.contentSize.height, 0);

NSLog(@"top inset: %f", topInset);

UIEdgeInsets contentInset = tableView.contentInset;
contentInset.top = topInset;
NSLog(@"inset: %f, %f : %f, %f", contentInset.top, contentInset.bottom, contentInset.left, contentInset.right);

NSLog(@"table height: %f", CGRectGetHeight(self.messagesTableView.frame));

UIViewAnimationOptions options = UIViewAnimationOptionBeginFromCurrentState;
[UIView animateWithDuration:animated ? 0.25 : 0.0 delay:0.0 options:options animations:^{
tableView.contentInset = contentInset;

} completion:^(BOOL finished) {
}];
}

Note: to view existing messages from array, you have to include this also.

- (void)viewDidLayoutSubviews {
[self updateContentInsetForTableView:self.messagesTableView animated:NO];
}

关于ios - 在底部添加单元格并滚动 UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33507208/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com