Reputation: 377
My tableview is having a list of cells which has over 50 datas and I do not want to show over 50 cells in my tableView. I only want to show 5 cells per page and whenever I scroll, my page number can increase/decrease.
I would like to scroll down and my app goes to the next page, while I scroll up and my app goes to the previous page. How should I do this?
override func viewDidLoad() {
super.viewDidLoad()
updatePropertyListWithDistrict(district: "ABC")
}
var currentPage : Int = 1
var listLimit : Int = 5
// getting property list
func updatePropertyListWithDistrict(district: String) {
PSPWCFService.sharedClient.PropertyList(district: district, PageNumber: currentPage, PageSize: listLimit) { (json, error) in
MBProgressHUD.hide(for: self.view, animated: true)
if let error = error {
print(error.localizedDescription)
return
}
let jsonArray = json?.array
for object in jsonArray! {
let newProperty: Property = Property(json: object)
self.properties.append(newProperty)
}
self.tableView.reloadData()
if (self.properties.count == 0)
{
let alertController = UIAlertController(title: "Alert", message:
"No listings available in the area. ", preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil))
self.present(alertController, animated: true, completion: nil)
}
}
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
//Bottom Refresh
if scrollView == tableView{
if ((scrollView.contentOffset.y + scrollView.frame.size.height) >= scrollView.contentSize.height)
{
currentPage += 1
self.tableView.reloadData()
}
}
}
Upvotes: 0
Views: 1634
Reputation: 605
you just need to enable the paging of the table view from the attribute inspector under the section scroll view.
Just click on the table view in the storyboard, goto attribute inspector, under Scroll View section just check the option 'Paging Enabled'
declare two variables as follows
var contentOffset:CGFloat = 0
var page = 0
then
override func viewDidLoad() {
super.viewDidLoad()
page = 1
}
then implement the method of scrollView
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
print(scrollView.contentOffset)
if scrollView.contentOffset.y > contentOffset {
page += 1
pageNumberLabel.text = page.description
} else if scrollView.contentOffset.y < contentOffset {
page -= 1
pageNumberLabel.text = page.description
}
contentOffset = scrollView.contentOffset.y
}
this will do the work for you but there's a problem in it when you slowly scroll the tableView, it only scrolls some rows not all which are displayed. Unfortunately can't find solution for that right now but will try for sure in free time.
Upvotes: 1