Monday, November 28, 2016

Swift 3 UITableView Pagination

We can use UIRefreshControl for ‘Pull To Refresh’ functionality on a tableview. But, What if we have kind of pagination like we need to display only specific page records like, If you are in first page and per page only 10 records, we need to display only those 10 records. After that If user pulls up the table, next page records and If user pulls down the table, previous page records as shown below.

(Scroll Down)



(Scroll Up)

It becomes use r friendly If we display the text as shown in the above picture for both pull up and down. The text on the UITableView background tells the user whether there is previous page or next page available to pull down or up for refreshing records.

In this post I am not going to talk about how to do pull up and down, rather I am going explain about adding those labels to the background view of UITableView.


  
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        if (self.tableViewRank.backgroundView == nil) {
            
            let bgView = UIView.init(frame: self.tableViewRank.frame)
            
            let topLabel = UILabel.init(frame: CGRect.init(x: 0, y: 20, width: 
            self.tableViewRank.frame.size.width, height: 30))
            topLabel.text = "*** No NEW posts to fetch ***"
            topLabel.textAlignment = .center
            topLabel.textColor = UIColor.blue
            topLabel.adjustsFontSizeToFitWidth  = true
            topLabel.font = UIFont(name: "Trebuchet MS", size: 18.0)
            
            let bottomLabel = UILabel.init(frame: CGRect.init(x: 0, y: 
            self.tableViewRank.frame.size.height-20, width:      
            self.tableViewRank.frame.size.width, height: 30))
            bottomLabel.text = "*** No OLD posts to fetch ***"
            bottomLabel.textAlignment = .center
            bottomLabel.textColor = UIColor.magenta
            bottomLabel.adjustsFontSizeToFitWidth  = true
            bottomLabel.font = UIFont(name: "Trebuchet MS", size: 18.0)
                        
            bgView.addSubview(topLabel)
            bgView.addSubview(bottomLabel)
            
            
            self.tableViewRank.backgroundView = bgView
        }

    } 



I have just added two labels to the tableview’s background view and adjusted label frames, one from the top and one from the bottom. In this way, users can see whether there are any new posts available by just scrolling down the table and any old posts still available by just scrolling up the table. If any new or old posts are available users can go for pulling the table up/down upon which we need to call service and fetch records.

Hope this post is useful. Feel free to comment incase of any queries.



No comments:

Post a Comment