简体   繁体   English

Swift 1.2-为什么我的UIPickerView不显示我的数据?

[英]Swift 1.2 - Why isn't my UIPickerView displaying my data?

I have a UIPickerView which I load with data I download from a MySQL database. 我有一个UIPickerView,它加载了从MySQL数据库下载的数据。 The data downloads and fills an array, and then I use that array as the source of data for my pickerView through the delegate methods. 数据下载并填充一个数组,然后通过委托方法将该数组用作我的pickerView的数据源。

My issue is, everything works fine, except that the pickerView doesn't visibly fill for a good 20 seconds after the array has been filled. 我的问题是,一切正常,除了在数组已填充后的20秒内,pickerView不能明显填充。 I have tried running all sorts of self.view.LayoutIfNeeded() and the like, and have plenty of pickerView.reloadAllComponents() but it still refuses to load visibly. 我已经尝试运行各种self.view.LayoutIfNeeded()之类的东西,并且有很多pickerView.reloadAllComponents()但是它仍然拒绝加载。 However, if the user taps on the pickerView, or changes it value (even though it is visibly empty), the data suddenly appears. 但是,如果用户点击pickerView或更改其值(即使它显然是空的),则数据会突然出现。 I have tried programmatically selecting each row to try and force it to display, but that hasn't worked. 我尝试以编程方式选择每一行以尝试强制其显示,但是这没有用。

Here is my code to download the data (which is run on viewDidLoad ): 这是我的代码,用于下载数据(在viewDidLoad上运行):

func RetreiveStaff() {
    SetProgramMode()

    self.aUsers = [User]()
    self.pkvUser.reloadAllComponents()

    if self.booCurrentDataVersion == true {

        var url:NSURL = NSURL(string: "http://www.website.com.au/retrievestaff.php")!
        let task:NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data:NSData!, response:NSURLResponse!, error:NSError!) -> Void in
            if error == nil {
                let dataArray:[AnyObject] = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! [AnyObject]
                for data in dataArray {
                    let dictionary:[String:String] = data as! [String:String]
                    if dictionary["StaffID"] != nil {

                        var newUser:User = User()
                        newUser.name = dictionary["LastName"]! + ", " + dictionary["FirstName"]!
                        newUser.id = dictionary["StaffID"]!.toInt()!
                        self.aUsers.append(newUser)

                        self.pkvUser.reloadAllComponents()
                        self.booDownloadedUsers = true
                    } else {
                        let actionSheet:UIAlertController = UIAlertController(title: "No Users Downloaded", message: "Please ensure a user has been entered in Access and then restart the app.", preferredStyle: UIAlertControllerStyle.Alert)
                        let firstAlertAction:UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {
                            (alertAction:UIAlertAction!) in
                        })
                        actionSheet.addAction(firstAlertAction)
                        self.presentViewController(actionSheet, animated: true, completion: nil)
                    }
                    self.pkvUser.reloadAllComponents()
                }
                println("\(self.aUsers.count) Staff Downloaded")
                self.pkvUser.reloadAllComponents()
                self.view.setNeedsLayout()
            } else {
                let actionSheet:UIAlertController = UIAlertController(title: "Connection Error", message: "\(strAppName) was unable to load data.  Check you are connected to the internet and restart the app.", preferredStyle: UIAlertControllerStyle.Alert)
                let firstAlertAction:UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {
                    (alertAction:UIAlertAction!) in
                })
                actionSheet.addAction(firstAlertAction)
                self.presentViewController(actionSheet, animated: true, completion: nil)
            }
        })

        task.resume()

    }
}

Here are my pickerView delegate methods: 这是我的pickerView委托方法:

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
    return self.aUsers[row].name
}

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    if count(self.aUsers) > 0 {
        strSelectedUser = self.aUsers[row]
    }
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return self.aUsers.count
}

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

where aUsers is an array of custom 'User' objects that I created. 其中aUsers是我创建的自定义“用户”对象的数组。

What do I need to do to get the view to refresh/reload/display the data because I know the data is there. 我需要做些什么才能使视图刷新/重新加载/显示数据,因为我知道数据在那里。 I also understand that I am downloading it asynchronously and that can cause issues like this, but the data downloads almost instantly, and I don't understand why the view won't keep up. 我还了解到我正在异步下载它,这可能会导致类似的问题,但是数据几乎是立即下载的,而且我不理解为什么视图无法跟上。

Thanks in advance. 提前致谢。

It's probably because you always have to update the UI in main threads, so once you have loaded the data (after you for loop I think) when you want to call the reloadAllComponents() you have to do it like below. 可能是因为您总是必须在主线程中更新UI,所以一旦加载了数据(我认为是在for循环之后),则当您要调用reloadAllComponents() ,必须像下面那样进行操作。

let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT

dispatch_async(dispatch_get_global_queue(priority, 0)) {
    dispatch_async(dispatch_get_main_queue()) {
        self.pkvUser.reloadAllComponents()
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM