简体   繁体   English

iOS - UITableView 不滚动到底部

[英]iOS - UITableView not scrolling to bottom

I am building a chat app in iOS but I have some problems with the UITableView displaying all the messages.我正在 iOS 中构建一个聊天应用程序,但在 UITableView 显示所有消息时遇到了一些问题。 I want the table view to be scrolled to the bottom on load so users can see the latest messages when they open the app.我希望表格视图在加载时滚动到底部,以便用户在打开应用程序时可以看到最新消息。

To do this I added this code in my function refreshing the data:为此,我在刷新数据的函数中添加了此代码:

    NSIndexPath* ipath = [NSIndexPath indexPathForRow: [self.messageOnTimeline numberOfRowsInSection:0]-1 inSection: 0];
    [self.messageOnTimeline scrollToRowAtIndexPath: ipath atScrollPosition: UITableViewScrollPositionTop animated: YES];

This worked fine until I added a header to the tableview.这工作正常,直到我向 tableview 添加标题。 I added the following code and now it doesn't scroll to the bottom when I load the app:我添加了以下代码,现在加载应用程序时它不会滚动到底部:

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 30)];
    return view;
}

Does anyone knows why?有谁知道为什么?

Many thanks for your help非常感谢您的帮助

Add this code in you viewDidload :在您的viewDidload添加此代码:

Swift 5斯威夫特 5

let indexPath = IndexPath(item: <Row Index>, section: <Section Index>)
tableView.reloadRows(at: [indexPath], with: .automatic)

Objective C目标 C

NSIndexPath *myIndexPath = [NSIndexPath indexPathForRow:AddYourLastIndex inSection:0];
[self.tbl_presentation selectRowAtIndexPath:myIndexPath animated:YES scrollPosition:UITableViewScrollPositionBottom];

试试这个代码。它会滚动到 tableview 的底部

 [self.tableview setContentOffset:CGPointMake(0, self.tableview.contentSize.height-self.tableview.frame.size.height) animated:YES];

@Darshan Kunjadiya answer is right. @Darshan Kunjadiya 答案是正确的。 Even we can achieve the same in storyboard.即使我们可以在故事板中实现相同的效果。

Select tableView --> from the storyboard control click on 'add Missing constraints'.选择 tableView --> 从情节提要控件中单击“添加缺少的约束”。 That will add the constraint to tableView and View.这会将约束添加到 tableView 和 View。

That helped me to resolve this issue.这帮助我解决了这个问题。 A screen_shot attached for reference.附上截图以供参考。 screen_shot Link 截图链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM