如何在UITableView SWIFT中加载更多单元格

问题描述 投票:0回答:3

我有一个UITableViewController(而不是PFQueryTableViewController)来显示我的查询结果,我有一个存储文本的数组。由于查询会获取大量数据,因此一旦用户滚动到底部,我希望我的tableView能够加载更多结果。有很多解决方案,但他们要么是JSON,要么是ObjectiveC,他们看起来对我很模糊,因为我只是一个初学者。

class queryResultsViewController: UITableViewController {

var texts = [String]()


override func viewDidLoad() {
    super.viewDidLoad()

    let query = PFQuery(className: "allPosts")

    query.whereKey("userId", equalTo: (PFUser.currentUser()?.objectId)!)
    query.orderByDescending("createdAt")

    query.findObjectsInBackgroundWithBlock { (posts, error) -> Void in

        if let posts = posts {

            self.texts.removeAll(keepCapacity: true)

            for post in posts {

                self.captionOne.append(post["text"] as! String)

                self.tableView.reloadData()
            }
        }
    }
}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return texts.count
}


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

    cell.TextView.text = texts[indexPath.row]

    return cell
}
swift uitableview pfquery
3个回答
1
投票

要检测用户何时滚动到UITableView的底部,您可以实现UIScrollView委托方法scrollViewDidScroll:

一个示例实现(从:https://stackoverflow.com/a/5627837/3933375转换为Swift)

override func scrollViewDidScroll(scrollView: UIScrollView) {
    let offset = scrollView.contentOffset
    let bounds = scrollView.bounds
    let size = scrollView.contentSize
    let inset = scrollView.contentInset
    let y = CGFloat(offset.y + bounds.size.height - inset.bottom)
    let h = CGFloat(size.height)

    let reload_distance = CGFloat(10)
    if(y > (h + reload_distance)) {
        print("load more rows")
    }
}

当触发时,您可以从解析中下载更多结果,将它们添加到UITableView的数据源并调用重新加载数据。

此外,查看代码时,您可能需要调用dispatch_async,因为您尝试更新后台块中的UI,例如

dispatch_async(dispatch_get_main_queue()) { () -> Void in
        self.tableview.reloadData()
    }

编辑 从Parse加载更多结果

let query = PFQuery(className: "allPosts")

query.whereKey("userId", equalTo: (PFUser.currentUser()?.objectId)!)
query.orderByDescending("createdAt")

query.limit = 50 // or your choice of how many to download at a time (defaults to 100)
query.skip = 50 // This will skip the first 50 results and return the next limit after. If

query.makeRequest......

在完成处理程序中,确保将结果附加到整个数据源(在您的情况下为texts),并调用重新加载数据。


0
投票

如何在UIToolBar中仅显示20个(例如)行并在屏幕底部添加“下一步”按钮?当用户点击按钮时,显示第21-40行等等。您还可以添加“上一步”按钮以向后移动。

- (void)setUpToolbar
{
// add a toolbar with a prev and next button
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle: @""
                                                                         style: UIBarButtonItemStylePlain
                                                                        target: nil
                                                                        action: nil];

UIBarButtonItem *flexibleItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace
                                                                              target: nil
                                                                              action: nil];

self.prevButton = [[UIBarButtonItem alloc] initWithTitle: NSLocalizedString(@"Prev", nil)
                                                   style: UIBarButtonItemStylePlain
                                                  target: self
                                                  action: @selector(clickedPrevButton:)];

self.nextButton = [[UIBarButtonItem alloc] initWithTitle: NSLocalizedString(@"Next", nil)
                                                   style: UIBarButtonItemStylePlain
                                                  target: self
                                                  action: @selector(clickedNextButton:)];

self.nextButton.enabled = NO;
self.prevButton.enabled = NO;
self.page = 1;

self.toolbarItems = @[self.prevButton, flexibleItem, self.nextButton];
}

- (void) clickedNextButton: (id) sender
{    
if ([self.nextButton.title isEqualToString: NSLocalizedString(@"More Results", nil)])
{
    self.offset += kSearchLimit;
    self.nextButton.title = NSLocalizedString(@"Next", nil);
    self.page += 1;

    [self searchDatabase];
}
else
{
    self.page += 1;

    if ((self.page - 1) * kEntriesToDisplay > self.searchResults.count)
    {
        self.nextButton.enabled = NO;
    }

    if (self.page * kEntriesToDisplay == self.searchResults.count)
    {
        self.nextButton.enabled = YES;
        self.nextButton.title = NSLocalizedString(@"More Results", nil);
    }

    self.prevButton.enabled = YES;

    [self updateSearchUI];        
}
}

- (void) clickedPrevButton: (id) sender
{
self.page -= 1;

if (self.page == 1)
    self.prevButton.enabled = NO;

self.nextButton.title = NSLocalizedString(@"Next", nil);
self.nextButton.enabled = YES;

[self updateSearchUI];
}

0
投票

这是在load more处理UITableView的正确方法。为了避免波动,下面的方法在滚动视图停止时调用。

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    let offsetY = scrollView.contentOffset.y
    let scrollHeight = scrollView.frame.size.height

    let endScrolling = offsetY + scrollHeight

    if endScrolling >= scrollView.contentSize.height {
        //Load more logic
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.