我尝试运行一个在 iOS 14/15/16 上完美运行的简单代码,但现在在 iOS 17 上使用 Xcode 15 时,它不再起作用了。我将附加下面的代码,显示带有
UIRefreshControl
的表格视图,它将在获取请求之前运行 beginRefreshing()
,但刷新控件在 iOS 17 上不再显示,我收到此警告,表示刷新控制在屏幕外接收开始刷新。
这里是使用
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()
}
}
}
您是否知道对此有什么解决办法,以便即使在 iOS 17 上也能以相同的方式运行,而不使用
viewDidAppear
或 viewWillAppear
方法,因为我希望每个视图生命周期只调用一次 fetch ?
在 iOS 17 中,苹果引入了一种新的生命周期方法:viewisappearing,它还具有 iOS 13+ 向后兼容性。
refreshControl.beginRefreshing() 应该在 viewIsAppearing 中调用 https://developer.apple.com/documentation/uikit/uiviewcontroller/4195485-viewisappearing
您可以参考以下链接来解决此问题。 Apple 在 iOS 17 中创建了新的生命周期方法viewIsAppearing。 https://www.youtube.com/watch?v=n9ObNkPP5GY&t=410s