修复 iOS 拉动刷新动画

asr*_*ama 1 uitableview ios pull-to-refresh swift

这是我的刷新控件代码。(代码已更新为整个 ViewController 代码以便更好地理解)

import UIKit

class AirportTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, AirportRequestDelegate {


    @IBOutlet weak var airportTable: UITableView!
    var airportRequest = AirportRequest()
    var airportList = [AirportDetail]()
    var refreshControl = UIRefreshControl()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "Airport List"
        airportTable.delegate = self
        airportRequest.delegate = self
        airportRequest.fetchAirports()
        airportTable.dataSource = self
        refreshControl.addTarget(self, action: #selector(refresh), for: UIControl.Event.valueChanged)
        airportTable.addSubview(refreshControl)

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return airportList.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let myCell = airportTable.dequeueReusableCell(withIdentifier: "airportTableCell", for: indexPath)
        myCell.textLabel?.text = self.airportList[indexPath.row].AirportName
        myCell.detailTextLabel?.text = self.airportList[indexPath.row].StationName
        myCell.accessoryType = .disclosureIndicator
        return myCell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.airportTable.deselectRow(at: indexPath, animated: true)
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if  editingStyle == .delete {
            self.airportList.remove(at: indexPath.row)
            airportTable.deleteRows(at: [indexPath], with: .top)
        }
    }


// The AirportRequestDelegate adds this function and is called once airport list is fetched
    func didUpdateAirports(_ airportRequest: AirportRequest, airports: [AirportDetail]) {

// copies the airport list to a local variable so that it can be used with the tableView delegate functions
        self.airportList = airports

// updating the UI
        DispatchQueue.main.async {
            self.airportTable.reloadData()
            self.refreshControl.endRefreshing()
        }
    }

    @objc func refresh(sender: UIRefreshControl) {
        airportRequest.fetchAirports()
    }


}

Run Code Online (Sandbox Code Playgroud)

在下图中,您可以看到动画没有按预期工作。我该如何解决。最好我希望动画继续,直到 tableView 更新。

在此处输入图片说明

小智 5

添加刷新控件作为子视图可​​能是一个问题。UITableView 现在具有刷新控件的属性。这里你有苹果文档的描述,你应该如何实现它:https : //developer.apple.com/documentation/uikit/uirefreshcontrol