ios UITableView 分页 - 底部刷新以在 Swift 中加载新数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35495750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:33:13  来源:igfitidea点击:

UITableView Pagination - Bottom Refresh to Load New Data in Swift

iosswiftswift3swift2

提问by Chris G.

I am trying to implement loading data from my backend with pagination. I have seen this, but it loads all the data, all then time. Is this the right way or am I doing something wrong?

我正在尝试使用分页从我的后端加载数据。我已经看到了这一点,但它一直在加载所有数据。这是正确的方法还是我做错了什么?

Thanks in advance.

提前致谢。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell

    print(indexPath.row)

    if (indexPath.row + 1 < self.TotalRowsWithPages) {
        cell.textLabel?.text = "\(self.myarray!.[indexPath.row].body)"
    } else {

        cell.textLabel?.text = "Loading more data...";

        // User has scrolled to the bottom of the list of available data so simulate loading some more if we aren't already
        if (!self.isLoading) {
            self.isLoading = true;
            self.TotalRowsWithPages = self.TotalRowsWithPages + self.PageSize
            self.getmoredata()
        }
    }

    return cell
}

回答by Sohil R. Memon

Nope, you can't go with that approach because cellForRowAtIndexPathis called many times and also it will take much time to check your conditions!

不,你不能采用这种方法,因为cellForRowAtIndexPath它被多次调用,而且检查你的条件需要很多时间!

Here, I have found a better option for UITableViewpagination.

在这里,我找到了一个更好的UITableView分页选项。

func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {

    //Bottom Refresh

    if scrollView == tableView{

        if ((scrollView.contentOffset.y + scrollView.frame.size.height) >= scrollView.contentSize.height)
        {
            if !isNewDataLoading{

                if helperInstance.isConnectedToNetwork(){

                    isNewDataLoading = true
                    getNewData()
                }
            }
        }
    }
}

isNewDataLoadingis Boolto check that UITableViewis loading new data or not!

isNewDataLoadingBool检查是否UITableView正在加载新数据!

Hope this helps!

希望这可以帮助!

回答by vien vu

You should implement load more in tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath). When last cell loading is display it mean user scroll to bottom so this is time you need load more data.

您应该在tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath). 当显示最后一个单元格加载时,这意味着用户滚动到底部,因此此时您需要加载更多数据。

Maybe it looks like this:

也许它看起来像这样:

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

    if !(indexPath.row + 1 < self.TotalRowsWithPages) {
        self.isLoading = true;
        self.getmoredata()

    }
}

回答by Alexey Lobanov

Try to check more data not in cellForRowAtIndexPath but in UIScrollViewDelegate - [DataModel sharedMyLibrary] is my data source class loading video data using RESTful API with pagination, it's fetchWithCompletion method fetch data from server in async, it's hasMore method says that server has more data (JSON contains next link) LibraryTableViewController - is subclass of the UITableViewController, hasMore - is the view at the bottom of the table view in the storyboard containing a button, so user has two options: scroll down or press the button. Also if this view is visible indicates that there are more data on the server. _canFetch prevents nested loading from the server.

尝试检查更多数据,而不是在 cellForRowAtIndexPath 中,而是在 UIScrollViewDelegate - [DataModel sharedMyLibrary] 是我的数据源类,它使用带分页的 RESTful API 加载视频数据,它的 fetchWithCompletion 方法异步从服务器获取数据,它的 hasMore 方法表示服务器有更多数据( JSON 包含下一个链接)LibraryTableViewController - 是 UITableViewController 的子类,hasMore - 是包含按钮的故事板中表格视图底部的视图,因此用户有两个选择:向下滚动或按下按钮。此外,如果此视图可见,则表明服务器上有更多数据。_canFetch 防止从服务器嵌套加载。

``

``

@interface LibraryTableViewController () <UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *hasMore;
@end
@implementation LibraryTableViewController
{
    __block volatile uint8_t _canFetch;
}
@synthesize hasMore = _hasMore;
- (void)viewDidLoad
{
    _canFetch = 0x80;
    [super viewDidLoad];
    [self fetchVideos:NO];
}
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    CGPoint offset = [scrollView contentOffset];
    if ([[DataModel sharedMyLibrary] hasMore])
    {
        if (((velocity.y > 0.0) && (offset.y > (*targetContentOffset).y)) || ((velocity.x > 0.0) && (offset.x > (*targetContentOffset).x)))
        {
            [self fetchVideos:NO];
        }
    }
    else
    {
        [_hasMore setHidden:YES];
    }
}
- (IBAction)moreVideos:(UIButton *)sender
{
    [self fetchVideos:NO];
}
- (IBAction)doRefresh:(UIRefreshControl *)sender
{
    [sender endRefreshing];
    [[DataModel sharedMyLibrary] clear];
    [self fetchVideos:YES];
}
- (void)fetchVideos:(BOOL)reload
{
    if (OSAtomicTestAndClear(0, &(_canFetch)))
    {
        __weak typeof(self) weakSelf = self;
        [[DataModel sharedMyLibrary] fetchWithCompletion:^(NSArray *indexPathes) {
            dispatch_async(dispatch_get_main_queue(), ^{
                __strong typeof(self) strongSelf = weakSelf;
                if (indexPathes != nil)
                {
                    if (reload)
                    {
                        [[strongSelf tableView] reloadData];
                    }
                    else
                    {
                        [[strongSelf tableView] beginUpdates];
                        [[strongSelf tableView] insertRowsAtIndexPaths:indexPathes withRowAnimation:UITableViewRowAnimationAutomatic];
                        [[strongSelf tableView] endUpdates];
                    }
                }
                else
                {
                    [[strongSelf tableView] reloadData];
                }
                [strongSelf->_hasMore setHidden:![[DataModel sharedMyLibrary] hasMore]];
                strongSelf->_canFetch = 0x80;
            });
        }];
    }
}

``

``