Reputation: 373
I would like to load more data and create additional cells when the user scrolls to the bottom of the table. I'm using JSON data and MySql.
func dataJsonFromURL(url:String)->NSArray
{
if let data = NSData(contentsOfURL: NSURL(string: url)!) {
return ((try! NSJSONSerialization.JSONObjectWithData(data, options: [])) as! NSArray)
}
else{
return data
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("NCell", forIndexPath: indexPath) as! TableViewCell22
cell.backgroundColor = UIColor .clearColor()
let mindata = (data[indexPath.row] as! NSDictionary)
}
Upvotes: 35
Views: 60195
Reputation: 4523
Xcode 8, Swift 3
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let lastElement = dataSource.count - 1
if !loadingData && indexPath.row == lastElement {
indicator.startAnimating()
loadingData = true
loadMoreData()
}
}
Upvotes: 22
Reputation: 586
i used this method and it's works for me
func scrollViewDidScroll(scrollView: UIScrollView) {
let offsetY = scrollView.contentOffset.y
let contentHeight = scrollView.contentSize.height
if offsetY > contentHeight - scrollView.frame.size.height {
loadMoreDataFromServer()
self.tableView.reloadData()
}
}
Upvotes: 6
Reputation: 843
you have to use this method
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
let lastElement = dataSource.count - 1
if indexPath.row == lastElement {
// handle your logic here to get more items, add it to dataSource and reload tableview
}
}
Upvotes: 62
Reputation: 1528
You need one very handy delegate method:
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell , forRowAtIndexPath indexPath: NSIndexPath) {
}
This method gives your the current displayed row. Use the indexPath it provides to determine when you are nearing the bottom of the table. Then get more JSON and reload the table.
Upvotes: 1
Reputation: 1574
Its Called pagination to tableview. Pagination is used to show large data on a table in an effective way. Here's you can get nice tutorial for objective-c and for swift look at this Question.
And you can download example in swift from Here.
Upvotes: 1
Reputation: 4941
Use this library. https://github.com/samvermette/SVPullToRefresh
This will full fill your requirements. You just need to change page number or timestamp every time, when new web-service will be called.
Upvotes: -9