UIRefreshControl 在 iOS 17 上不显示(收到 offscreen beginRefreshing 警告)

Sp1*_*ire 3 tableview ios uirefreshcontrol xcode15 ios17

我尝试运行一个在 iOS 14/15/16 上完美运行的简单代码,但现在在 iOS 17 上使用 Xcode 15 时,它不再起作用了。我将附加下面的代码,显示一个表视图,该视图UIRefreshControl将在获取请求之前运行beginRefreshing(),但刷新控件在 iOS 17 上不再显示,并且我收到此警告,表示刷新控件收到了屏幕外的 beginRefreshing。

在此输入图像描述

DispatchQueue.main.asyncAfter以下是使用显示简单表视图来模拟获取请求的代码。如果您尝试在 iOS 17 上运行它,刷新控件将不会在模拟提取请求之前显示。

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    private let tableView = UITableView()
    private let cellIdentifier = "cellIdentifier"
    private let data = ["Cell 1", "Cell 2"]
    private let refreshControl = UIRefreshControl()

    override func viewDidLoad() {
        super.viewDidLoad()
        configureTableView()
        
        refreshControl.beginRefreshing()
        
        // Simulate fetch request
        DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
            self.setDataSource()
        })
    }
    
    private func configureTableView() {
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
        refreshControl.addTarget(self, action: #selector(refreshData), for: .valueChanged)
        tableView.refreshControl = refreshControl
        
        tableView.frame = view.bounds
        tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        view.addSubview(tableView)
    }
    
    private func setDataSource() {
        tableView.dataSource = self
        tableView.reloadData()
        refreshControl.endRefreshing()
    }
    
    // MARK: - UITableViewDataSource
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
        cell.textLabel?.text = data[indexPath.row]
        return cell
    }
    
    // MARK: - Refresh Control Action
    
    @objc private func refreshData() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
            self.refreshControl.endRefreshing()
            self.tableView.reloadData()
        }
    }
}

Run Code Online (Sandbox Code Playgroud)

您是否知道对此有什么解决办法,以便即使在 iOS 17 上也能以相同的方式运行,而不使用viewDidAppearviewWillAppear方法,因为我希望每个视图生命周期只调用一次 fetch ?

小智 5

在 iOS 17 中,苹果引入了一种新的生命周期方法:viewisappearing,它还具有 iOS 13+ 向后兼容性。

freshControl.beginRefreshing() 应该在 viewIsAppearing 中调用 https://developer.apple.com/documentation/uikit/uiviewcontroller/4195485-viewisappearing