Home > Software engineering >  Refresh UITable content by scrolling table from top to bottom
Refresh UITable content by scrolling table from top to bottom

Time:10-08

I m building ios application using swift5. So in my view, I create TableView to display some information. When the user open the view, I call a web service to retreive the data to show in my TableView. But I want also that the user can refresh the content of table as in normal application.

So this is the code of my table view:

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)  {

    }
    
}

Now when the user open the view, it can display this view:

enter image description here

Now if the user scroll the table from bottom to top, the table show the use other order, but when the user scroll the table from top to bottom and the table arrived at the first element, I want to call a method to get all new data and refresh the table content.

CodePudding user response:

You can use UIRefreshControl (link to docs) the simple way of using it would be so:

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
 
}

And now in you viewDidLoad method make sure to call the setupTableView method.

  • Related