0

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?

4
  • Does something not work when you implement it the way you show? Commented Nov 8, 2015 at 11:12
  • yes it does not update the values Commented Nov 8, 2015 at 11:12
  • Your code seems to be valid. Make sure than buttonClicked is called when your button is clicked. Commented Nov 8, 2015 at 11:16
  • Yes, the buttonClicked is called but it is not updating the values :( Commented Nov 8, 2015 at 11:20

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.