sam
sam

Reputation: 253

Update picker values on button click swift 1.2

I have a working picker view with following lines of code

@IBOutlet var myPicker: UIPickerView!

var colors: [String] = ["red","green","blue"]

override func viewDidLoad() {
        super.viewDidLoad()     

        myPicker = UIPickerView()
        myPicker.dataSource = self
        myPicker.delegate = self
}

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

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

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

i have a button when i click i want to remove all the old values (i'e red, green and blue) and update with the new values (yellow, black)

func buttonClicked(sender: UIButton!) {
        var btn:UIButton = sender;
        colors = ["yellow", "black”]
        myPicker.reloadAllComponents()
}

but unfortunately the above code is not working, i'm a newbie in swift and dont know how to implement this, can someone please help me on this?

Upvotes: 0

Views: 798

Answers (1)

matt
matt

Reputation: 535231

The problem is that you have two picker views. The source of the issue is these lines:

override func viewDidLoad() {
    super.viewDidLoad()
    myPicker = UIPickerView() // this is the problem
    myPicker.dataSource = self
    myPicker.delegate = self
}

You are setting myPicker to a completely new and different UIPickerView which you are creating in that line (the one that I've marked with a comment). This is not the picker view that is already in your interface (the one you set up in the storyboard). And you never place this one into the interface. Thus:

  • The picker view in the interface is left untouched by all your code; the one in the interface never gets a data source, never gets a delegate, and never reloads anything.

  • The picker view you create in these lines does all those things, but it is not in the interface so you don't see it do anything.

Upvotes: 1

Related Questions