Search code examples
iosiphoneswiftuipickerview

Swift - UIPickerView - Components still hidden after using "reloadAllComponents"


i'm using web service to update components of uipickerview .

after appending all components to pickCityOptions array i call "reloadAllComponents" to update uipickerview.

i works great for updating components, but after updating all components still hidden till I tab on the picker , then all components appears.

@IBOutlet weak var pickCity: UIPickerView!

let defaults = NSUserDefaults.standardUserDefaults()

var pickCityOptions = [String]()
var items = [[String:String]()]


override func viewDidLoad() {
    super.viewDidLoad()

    self.pickCity.dataSource = self;
    self.pickCity.delegate = self;

    let urlPath = "http://www.waelmoharram.com/dalel/api/v1/cities"

    let url = NSURL(string: urlPath)

    let session = NSURLSession.sharedSession()

    let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in

        if error != nil {

            print(error)

        } else {


            do {
                let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers ) as! NSArray


                var item:AnyObject

                for i in 0 ... jsonResult.count - 1 {

                    self.items.append([String:String]())

                    item = jsonResult[i]



                    self.items[i]["id"] = "\(item["id"]!)" as NSString as String

                    self.items[i]["city_name"] = item["city_name"] as! NSString as String



                    self.pickCityOptions.append(self.items[i]["city_name"]!)

                }

                self.pickCity.reloadAllComponents()



            } catch {

                print(error)

            }


        }

    })

    task.resume()

    if let currentCityRow = self.defaults.stringForKey("city") {

        self.pickCity.selectRow(Int(currentCityRow)!, inComponent: 0, animated: true)

    }else{

        self.pickCity.selectRow(0, inComponent: 0, animated: true)

    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
    defaults.setObject(row, forKey: "city")

}


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

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

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return pickCityOptions[row]
}

Solution

  • You need to use pickCityOptions as NSMutableArray.Don't use pickCityOptions.append instead use pickCityOptions.addObject

        var pickCityOptions = NSMutableArray()
        pickCityOptions.addObject(self.items[i]["city_name"]!)