swift ios为uitableview添加无限滚动分页 [英] swift ios add infinite scroll pagination to uitableview
问题描述
我想知道tableview是否有任何内置函数来添加无限滚动/分页。
I wonder if tableview has any built-in function to add infinite scroll/pagination.
现在我的VC看起来像这样:
Right now my VC looks like this:
var data: JSON! = []
override func viewDidLoad() {
super.viewDidLoad()
//Init start height of cell
self.tableView.estimatedRowHeight = 122
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.delegate = self
self.tableView.dataSource = self
savedLoader.startAnimation()
//Load first page
loadSaved(1)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("aCell") as! SavedTableViewCell
let info = data[indexPath.row]
cell.configureWithData(info)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("WebSegue", sender: indexPath)
tableView.deselectRowAtIndexPath(indexPath, animated: false)
}
我通过给出函数使用 loadSaved(1)获取数据我要加载的当前页面。该函数使用alomofire发出API请求,然后填充 var data:JSON! = [] 与应显示的数据
I fetch my data using loadSaved(1) by giving the function the current page I want to load. The function makes a API request using alomofire then populate the var data: JSON! = [] with the data that should be displayed
所以我想要做的是当我滚动到tableview的底部 loadSaved( 2)应该调用将更多数据加载到tableview中
So what I want to do is when I scroll to the bottom of the tableview loadSaved(2) should be called loading more data into the tableview
推荐答案
UITableViewDelegate有一个表视图(_:将显示:for Row At:)实例方法告诉委托表格视图即将绘制特定行的单元格。
The UITableViewDelegate has a tableView(_:willDisplay:forRowAt:) instance method which "tells the delegate the table view is about to draw a cell for a particular row."
在您的情况下,我会使用类似这样的内容:
In your case I would use it something like this:
override open func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.row == data.count-1 { //you might decide to load sooner than -1 I guess...
//load more into data here
}
}
取决于你的代码,您可能需要对此进行一些检查,以确保如果您已加载所有数据,则不会以无限循环结束...
Depending on your code, you may need some checks around this to ensure you don't end up in an infinite loop if you've loaded all your data...
这篇关于swift ios为uitableview添加无限滚动分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!