gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:06:37 25 4
gpt4 key购买 nike

我有一个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
}

最佳答案

要检测用户何时滚动到 UITableView 底部,您可以实现 UIScrollView 委托(delegate)方法 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 的数据源中并调用重新加载数据。

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

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......



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

关于swift - 如何在 UITableView SWIFT 中加载更多单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35578598/

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