从上到下滚动 table 刷新 UITable 内容

Refresh UITable content by scrolling table from top to bottom

我正在使用 swift5 构建 ios 应用程序。 所以在我看来,我创建 TableView 来显示一些信息。当用户打开视图时,我调用 Web 服务来检索数据以显示在我的 TableView 中。但我还希望用户可以像在正常应用程序中一样刷新 table 的内容。

所以这是我的 table 视图的代码:

extension HomeVC : UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.arrListAll.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! homcell
        /*var arrList:[Result] = []
        if buttonTag == 0{
            arrList = self.arrListPending
        }else if buttonTag == 1{
            arrList = self.arrListProcess
        }else if buttonTag == 2{
            arrList = self.arrListCompleted
        }else if buttonTag == 3{
            arrList = self.arrListRejected
        }*/
        
        let order = self.arrListAll[indexPath.row]
            let arrayArticoli = order.itemData
            var strOrder:String = ""
            for i in 0..<arrayArticoli.count {
                var prodotto = arrayArticoli[i]
                strOrder += "\(prodotto.itemQuantity) x \(prodotto.itemName)\n"
                //devo verificare che ingredient name abbia qualcosa
                if(prodotto.itemName != nil &&
                    prodotto.ingredientName != "" ){
                    
                    var aggiunte = prodotto.ingredientName
                    var arr = aggiunte.components(separatedBy: ", ")
                    if(arr.count>0){
                        var cont = 0
                        for y in 0..<arr.count - 1 {
                            strOrder += (arr[y]) + ", "
                            if(cont == 2){
                                cont = 0
                                strOrder += "\n"
                            }
                            cont = cont + 1
                        }
                        if(i < (arrayArticoli.count - 1)){
                            strOrder += "\n"
                        }
                        
                    }
                }
            }
            var timeBooking:String? = order.timeBooking
            if ((timeBooking?.isEmpty) != nil){
                cell.lblTitlePrenotazione.text = "è una prenotazione, controlla l'orario \ndi prenotazione in fondo."
                cell.lblTitlePrenotazione.backgroundColor = UIColor.yellow
                cell.lbl_OrarioPrenotazione.text = "Prepara per le ore " + (timeBooking)!
                cell.lbl_OrarioPrenotazione.backgroundColor = UIColor.yellow
            }else{
                cell.lblTitlePrenotazione.text = ""
                cell.lbl_OrarioPrenotazione.text = ""
            }
            cell.lblTitleOrderDetail.text = "DETTAGLIO ORDINE:"
            cell.lblId.text = "ID : \(order.id)"
            cell.lbl_Name.text = order.userName
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            let date = formatter.date(from: order.dateTime)
            formatter.dateFormat = "dd/MM/yyyy HH:mm"
            cell.lbl_Date.text = "DATA : \(formatter.string(from: date!))"
            cell.lbl_Number.text = "Numero : \(order.mobile)"
            cell.lbl_OrderDetail.text = strOrder
            //cell.lbl_OrderDetail.sizeToFit();
            //cell.lbl_OrderDetail.adjustsFontSizeToFitWidth = false
            //cell.lbl_OrderDetail.lineBreakMode = .byTruncatingTail
            cell.lbl_OrderDetail.lineBreakMode = NSLineBreakMode.byWordWrapping

            cell.lbl_DeliveryCharge.text = "Consegna \(kCurrency):\(order.deliveryCoast)"
            let ordine = Double(order.totalOrder ?? "0.0")! + Double(order.deliveryCoast ?? "0.0")!
            cell.lbl_Total.text = "Totale \(kCurrency):\(ordine)"
           
            
            cell.lbl_Paynet.text = "Ordine\(kCurrency):\(order.totalOrder)"
            if(order.paymentType == "Cash"){
                cell.lbl_PaymentType.text = "Pagamento in contanti :"
            }else if(order.paymentType == "Card"){
                cell.lbl_PaymentType.text = "Pagamento con carta :"
            }
            
            cell.btn_messa.tag = indexPath.row
            cell.btn_messa.addTarget(self, action: #selector(goSendMessage), for: .touchUpInside)

            cell.btnccall.tag = indexPath.row
            cell.btnccall.addTarget(self, action: #selector(goReject), for: .touchUpInside)
            
            cell.btn_Wait.tag = indexPath.row
            cell.btn_Wait.addTarget(self, action: #selector(goAcceptMove), for: .touchUpInside)
            if(buttonTag == 0){
                if(order.status == self.st_pending){
                    cell.btn_Wait.setTitle("Accetta ordine",for: .normal)
                    cell.btn_Wait.isEnabled = true
                }else if(order.status == self.st_driver_rejected){
                    cell.btn_Wait.setTitle("Ordine rifiutato dal Runner",for: .normal)
                    cell.btn_Wait.isEnabled = false
                }
                
                cell.btn_Wait.backgroundColor = UIColor.systemOrange
            }else if(buttonTag == 1){
                if(order.status == self.st_driver_accept){
                    cell.btn_Wait.setTitle("Ordine accettato dal Runner",for: .normal)
                    cell.btn_Wait.isEnabled = true
                }else if(order.status == self.st_process){
                    cell.btn_Wait.setTitle("in Attesa che il Moover accetti",for: .normal)
                    cell.btn_Wait.isEnabled = false
                }else if(order.status == self.st_way){
                    cell.btn_Wait.setTitle("in Consegna",for: .normal)
                    cell.btn_Wait.isEnabled = false
                }
                cell.btn_Wait.backgroundColor = UIColor.systemOrange
                
            }else if(buttonTag == 2){
                cell.btn_Wait.setTitle("Ordine Consegnato",for: .normal)
                cell.btn_Wait.backgroundColor = UIColor.systemOrange
                cell.btn_Wait.isEnabled = false
            }else if(buttonTag == 3){
                cell.btn_Wait.setTitle("Ordine Cancellato",for: .normal)
                cell.btn_Wait.backgroundColor = UIColor.red
                cell.btn_Wait.isEnabled = false
            }
        
        
        return cell
    }
    
    func goHistoryOrder(indexRow indexRow: Int){
        let order = self.arrListAll[indexRow]
        if(order.status == self.st_driver_accept){
            let objVC = kStoryboardMain.instantiateViewController(withIdentifier: "HistoryDetailVC") as! HistoryDetailVC
            objVC.order = order
            self.navigationController?.pushViewController(objVC, animated: true)
        }
    }
    
    
    @objc func goAcceptMove(butt:UIButton)  {
        let order = self.arrListAll[butt.tag]
        if(order.status == self.st_pending){
            cambiaStatoOrdine(strStatu: "Process", strId: order.id)
        }else if(order.status == self.st_driver_accept){
            goHistoryOrder(indexRow: butt.tag)
        }
        
    }
    @objc func goSendMessage(butt:UIButton)  {
        let order = self.arrListAll[butt.tag]
        let objVC = kStoryboardMain.instantiateViewController(withIdentifier: "UserChat") as! UserChat
        objVC.receiverId = order.userID
        objVC.userName = order.userName
        self.navigationController?.pushViewController(objVC, animated: true)
    }
    @objc func goReject(butt:UIButton)  {

    }
    
}

现在当用户打开视图时,可以显示这个视图:

现在如果用户从下到上滚动 table,table 显示使用其他顺序,但是当用户从上到下滚动 table 并且table 到达第一个元素,我想调用一个方法来获取所有新数据并刷新 table 内容。

您可以使用 UIRefreshControl(link 到 docs),简单的使用方法如下:

func setupTableView() {
   //You can add tableView.delegate = self and
   // and tableView.dataSource = self here
   
   // And here is the code to setup the refresh control
   tableView.refreshControl = UIRefreshControl()
   tableView.refreshControl?.addTarget(self, action:
                                  #selector(handleRefreshControl),
                                  for: .valueChanged)
}

func handleRefreshControl() {
   //This method gets called when the user pulls to refresh on the table view so you can refresh the data source here and make sure to call .endRefreshing on the refresh control to stop the loading animation
 
}

现在在你的 viewDidLoad 方法中确保调用 setupTableView 方法。