ios - swift/iOS : UIPicker display is not refreshed until tapped after changing the datasource programmatically

标签 ios swift user-interface asynchronous picker

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

它最初有一个元素(用作标签),当 POST 请求被填充时,数据源被更改,我调用 picker.reloadAllComponents() 来刷新它。

运行时,屏幕上似乎没有任何反应,选择器也没有改变。但是一旦点击,新数据就会立即出现并且可以正常工作。似乎数据源更改工作正常,但显示在刷新之前不会更改。

有没有办法刷新它,或者改变数据源的不同方法

相关代码如下:

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()
}
}

最佳答案

在将异步标记添加到问题时想通了......好老橡皮鸭调试。

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

在这种情况下,替换

dossiers_picker.reloadAllComponents()

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

关于ios - swift/iOS : UIPicker display is not refreshed until tapped after changing the datasource programmatically,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45221065/

相关文章:

iphone - 我该如何限制 ipad 中的文件应用程序大小?

ios - TableView在View中覆盖整个屏幕

objective-c - UIViewController 知道它是被推送还是弹出?

json - 网络响应中同一 json 对象的不同 key 类型

user-interface - AppleScript:获取所有桌面上的窗口列表

ios - 如何在 Swift 4 中设置设备的闪光灯模式?

ios - 使用键检索 PFObject

ios - 如何在单击按钮时将 ImageView 添加到表格单元格中?

windows - QML 缩放不适用于非整数缩放因子

Java GUI JList 应用程序