IOS- UITableView 滚动回到顶部

IOS- UITableView scroll back to top

我在我的项目中使用自定义 UITableView 来显示数据它工作正常但是当我尝试将它滚动到底部时它不会在所需的单元格处停止它总是跳到 table。只显示 2-3 个单元格。 请建议添加什么来解决这个问题。

我尝试了很多在类似问题中回答的代码,但它们不起作用

i 使用以下代码 UITableView

newsFeedTable = [[UITableView alloc]init];
    CGFloat Ytablepadding = CGRectGetMaxY(homeView.frame)+60;
    CGFloat heighttable = 700;
    newsFeedTable.frame = CGRectMake(0,Ytablepadding, self.view.frame.size.width, heighttable);
    [self.view addSubview:newsFeedTable];
    newsFeedTable.delegate=self;
    newsFeedTable.dataSource= self;

您需要根据视图的高度调整 table 视图的高度,您正在制作子视图以查看 table 的最后一行或者更确切地说将其滚动到底部:

newsFeedTable.frame = CGRectMake(0,Ytablepadding, self.view.frame.size.width, self.view.frame.size.height - Ytablepadding);

并在 table 重新加载/弹出数据后将其滚动到最后一行,像这样以编程方式滚动它:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                [newsFeedTable reloadData];

                dispatch_async(dispatch_get_main_queue(), ^{
                    int lastRowNumber = [newsFeedTable numberOfRowsInSection:0] - 1; 
                    NSIndexPath* ip = [NSIndexPath indexPathForRow:lastRowNumber inSection:0];
                    [newsFeedTable scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionTop animated:NO];
                });

            });

        }];

在您的 viewDidload 中添加此代码:

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

您可以做的最简单的事情是: 打电话 [newsFeedTable setContentOffset:CGPointMake(0, CGFLOAT_MAX)] 会为所欲为。

UITableView是UIScrollView的子类,所以你也可以使用:

[newsFeedTable scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES]; 或者

[newsFeedTable setContentOffset:CGPointZero animated:YES];