Search code examples
swiftuipickerview

UIPickerView select first row, when hiding


I've made a toolbar for UIPickerView:

override func viewDidLoad() {
    pickerToolbar.barStyle = UIBarStyle.Default
    pickerToolbar.translucent = true
    pickerToolbar.tintColor = UIColor(red: 0.0, green: 112/255, blue: 186/255, alpha: 1.0)
    pickerToolbar.sizeToFit()

    let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "hidePicker()")
    let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "hidePicker()")

    pickerToolbar.setItems([cancelButton, spaceButton, doneButton], animated: false)
    pickerToolbar.userInteractionEnabled = true

    typePicker.addSubview(pickerToolbar)
}

func hidePicker() {
    typePicker.hidden = true
}

But when I tap "Done" or "Cancel" button, picker select first row and close. I don't want such a behavior, I just want to hide picker and leave selected value.

So, I have 2 questions:

  1. Why UIPickerView behave like this?
  2. How to prevent it?

Thanks for any help!


Solution


  • I found you have two errors. One is a typo for action. It has to be action: "hidePicker", no brackets according to your codes. The second one is your pickerToolbar should not be a subview of pickerView. Change it to self.view.addSubview(pickerToolbar) and you will see the change.

    Cheers,