Swift/iOS:只有在以编程方式更改数据源后点按之后,UIPicker的显示才会刷新 [英] Swift/iOS : UIPicker display is not refreshed until tapped after changing the datasource programmatically

查看:90
本文介绍了Swift/iOS:只有在以编程方式更改数据源后点按之后,UIPicker的显示才会刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有一个选择器,该选择器在POST请求后填充了来自服务器的数据.

In my app, I have a picker that's filled with data from my server after a POST request.

它最初具有一个元素(用作标签),并且在POST请求被填充时,数据源得到更改,我调用picker.reloadAllComponents()对其进行刷新.

It has one element initially (used as a label), and when the POST request is filled the datasource get changed and I call picker.reloadAllComponents() to refresh it.

运行此命令时,屏幕上没有任何显示,选择器没有更改.但是,一旦点击,新数据就会立即出现并且可以正常工作.似乎数据源更改可以正常工作,但是直到刷新后显示才会更改.

When this run, nothing appears to happen on screen, the picker doesn't change. But once tapped, the new data instantly appear and it works correctly. Seems like the data source change works correctly but the display doesn't change until refreshed.

是否有刷新它的方法,或者有另一种方法来更改数据源

Is there a way to refresh it, or a different method to change the datasource

以下是相关代码:

class MyController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

@IBOutlet weak var dossiers_picker: UIPickerView!
var pickerData: [Dossier] = [Dossier(nom: "Dossier", id: 0)]
// Dossier is just a tuple class with 2 attributes

override func viewDidLoad() {
    super.viewDidLoad()
    self.dossiers_picker.delegate = self
    self.dossiers_picker.dataSource = self
    getDossiers()
}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return pickerData.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return pickerData[row].nom
}

func getDossiers() {
    ... // Cut the code where I call the server to get the data, etc ...
    let task = session.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
                // check for fundamental networking error
                print("error=\(String(describing: error))")
                return
            }
        ... // get the data and turn it into an array of Dossier classes in var dossiers
        self.pickerData = dossiers
        dossiers_picker.reloadAllComponents()
    }
    task.resume()
}
}

推荐答案

在向问题中添加异步标记时发现了这一点...很好的老式橡皮鸭调试.

Figured it out when adding the asynchronous tag to the question... good old rubber duck debugging.

@rmaddy所说,所有UI更新都必须在主线程上完成.

As said by @rmaddy, all UI updates must be done on the main thread.

在这种情况下,请替换

dossiers_picker.reloadAllComponents()

使用

DispatchQueue.main.async {
    self.dossiers_picker.reloadAllComponents()
}

这篇关于Swift/iOS:只有在以编程方式更改数据源后点按之后,UIPicker的显示才会刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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