Search code examples
iosswiftdrop-down-menuuipickerview

Drop-down style UIPickerView?


I was wondering how to get a UIPickerView to slide up from the bottom of the screen after tapping on a drop-down style button. Like in the image below:

CloudConvert screenshot of a drop-down style UIPickerView

I've run into this type of picker views a lot in the apps that I use regularly, so honestly I was expecting to easily find this picker view by setting the UIPickerView's style property, or something like that. Is this even a UIPickerView or do I have to create this kind of view manually?


Solution

  • One way of doing this is to have a normal UITextField and then assign a UIPickerView as the inputView of that textfield. That way, instead of a keyboard appearing when you tap your textfield, you get your pickerview.

    Example

    First declare a normal UIPickerView instance:

    let yourPicker = UIPickerView()
    

    and an outlet to a UITextField:

    @IBOutlet weak var yourTextField: UITextField!
    

    In your viewDidLoad you tie the elements together

    yourPicker.delegate = self
    yourPicker.dataSource = self
    yourTextField.inputView = yourPicker
    

    And then you need to implement the required methods of UIPickerViewDelegate and UIPickerViewDataSource

    Finally. In pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) you update the value of your textfield:

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
       yourTextField.text = yourDataArrayUsedInThePicker[row]
    }
    

    Read more

    Description of inputView https://developer.apple.com/library/content/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/InputViews/InputViews.html

    A way better explaination than mine: Show UIPickerView text field is selected, then hide after selected

    Hope that helps you.