UITableView load more when scrolling to bottom like Facebook application

后端 未结 18 2174

I am developing an application that uses SQLite. I want to show a list of users (UITableView) using a paginating mechanism. Could any one please tell me how to load more dat

18条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 09:31

    Details

    • Swift 5.1, Xcode 11.3.1

    Solution

    Genetic UITableView Extension For Loadmore.

    add this UITableView + Extension in your new file

    extension UITableView{
    
        func indicatorView() -> UIActivityIndicatorView{
            var activityIndicatorView = UIActivityIndicatorView()
            if self.tableFooterView == nil{
                let indicatorFrame = CGRect(x: 0, y: 0, width: self.bounds.width, height: 40)
                activityIndicatorView = UIActivityIndicatorView(frame: indicatorFrame)
                activityIndicatorView.isHidden = false
                activityIndicatorView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin]
                activityIndicatorView.isHidden = true
                self.tableFooterView = activityIndicatorView
                return activityIndicatorView
            }else{
                return activityIndicatorView
            }
        }
    
        func addLoading(_ indexPath:IndexPath, closure: @escaping (() -> Void)){
            indicatorView().startAnimating()
            if let lastVisibleIndexPath = self.indexPathsForVisibleRows?.last {
                if indexPath == lastVisibleIndexPath && indexPath.row == self.numberOfRows(inSection: 0) - 1 {
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                        closure()
                    }
                }
            }
            indicatorView().isHidden = false
        }
    
        func stopLoading(){
            indicatorView().stopAnimating()
            indicatorView().isHidden = true
        }
    }
    

    Now, just add following line of code in UITableViewDelegate Method willDisplay Cell in your ViewController and make sure tableView.delegate = self

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        // need to pass your indexpath then it showing your indicator at bottom 
        tableView.addLoading(indexPath) {
            // add your code here
            // append Your array and reload your tableview
            tableView.stopLoading() // stop your indicator
        }
    }
    

    Result

    That's it.. Hope this helpful. Thank You

提交回复
热议问题