程序化.beginRefresh()不刷新UITableView中的数据 [英] Programmatic .beginRefresh() not refreshing data in UITableView

查看:72
本文介绍了程序化.beginRefresh()不刷新UITableView中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的TableViewController中,我有一个@objc函数,该函数使用 Alamofire 获取数据。当用户拉下触发拉动刷新时,该函数由refreshController调用。

In my TableViewController, I have an @objc function that fetches data using Alamofire. The function is called by the refreshController when the user pulls down to trigger a pull refresh.

拉动刷新的声明如下:

let refreshControl = UIRefreshControl()
tableView.refreshControl = refreshControl
self.refreshControl!.addTarget(self, action: #selector(refresh(sender:)), for: .valueChanged)

它运行的功能:

@objc func refresh(sender:AnyObject) {
    let defaults = UserDefaults.standard
    if let mode = defaults.string(forKey: defaultsKeys.mode) {
        self.mode = mode
    }
    self.tableData.removeAll()
    print(mode)
    Alamofire.request(mode).response { response in
        let xml = SWXMLHash.config {
            config in
            config.shouldProcessLazily = true
            }.parse(response.data!)
        for elem in xml["rss"]["channel"]["item"].all {
            self.tableData.append(elem["title"].element!.text)
        }
        print("Completed Data Gather")
        self.mainTable?.reloadData()
        self.refreshControl!.endRefreshing()
    }
}

问题当我尝试使用

self.refreshControl!.beginRefreshing()
self.refreshControl!.sendActions(for: .valueChanged)

函数执行(如在控制台中观察到的打印语句)和数据被获取,但tableView拒绝刷新。我知道数据已正确获取,因为下次用户再次手动拉出时,将使用新数据刷新tableView更新。

The function executes (as observed in the console due to the print statements) and the data is fetched, but the tableView refuses to refresh. I know the data is fetched properly because the next time the user manually pull refreshes the tableView updates with the new data.

TL; DR 当用户手动进行拉刷新时,tableView会正确地重新加载,但是当以编程方式使用拉刷新时,则不会重新加载。

TL;DR My tableView properly reloads when the user manually pull refreshes, but not when the pull refresh is called programmatically using.

推荐答案

注释,这是因为UI更新必须在主线程上分派。

As Paul mentioned in the comments, this is because UI updates must be dispatched on the main thread.

Alamofire是异步的,并且在后台线程上运行。话虽如此,您的Alamofire请求中的所有代码都将在后台线程上执行。

Alamofire is asynchronous and runs on a background thread. With that being said, all of the code within your Alamofire request will execute on the background thread.

要在主线程上执行代码,请使用以下代码: / p>

In order to execute code on the main thread, utilize the following:

DispatchQueue.main.async {
    // Update UI ie. self.mainTable?.reloadData()
}

这篇关于程序化.beginRefresh()不刷新UITableView中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆