Search code examples
iosswiftuibuttonuipickerview

Show a UIPickerView when a button is tapped


enter image description here

I want to open a UIPickerView on the click of this button. I had created this button and now when the user clicks on it I want to open a UIPickerView. I have seen many tutorials on the Internet but all of them are showing with:

textfield.inputview = uipker // i don't want to use extfield

But want to implement it without a textfield. Is it possible and if possible then tell me how can I do that.


Solution

  • If you want to do it from Interface Builder then you can add UIPickerView in your storyBoard and initially hide that UIPickerView and when your button tapped show it.

    If you want to do this by coding then you can try this.

    Define this as global.

    var toolBar = UIToolbar()
    var picker  = UIPickerView()
    

    Add below code inside your button tap action. I have added Done button in toolbar to dismiss picker.

    Note : I write entire code in button action if you don't want to do that just write all code in viewDidLoad and write only these line in your button action self.view.addSubview(picker) and self.view.addSubview(toolBar)

    @IBAction func YOUR_BUTTON__TAP_ACTION(_ sender: UIButton) {
        picker = UIPickerView.init()
        picker.delegate = self
        picker.dataSource = self
        picker.backgroundColor = UIColor.white
        picker.setValue(UIColor.black, forKey: "textColor")
        picker.autoresizingMask = .flexibleWidth
        picker.contentMode = .center
        picker.frame = CGRect.init(x: 0.0, y: UIScreen.main.bounds.size.height - 300, width: UIScreen.main.bounds.size.width, height: 300)
        self.view.addSubview(picker)
                
        toolBar = UIToolbar.init(frame: CGRect.init(x: 0.0, y: UIScreen.main.bounds.size.height - 300, width: UIScreen.main.bounds.size.width, height: 50))
        toolBar.barStyle = .blackTranslucent
        toolBar.items = [UIBarButtonItem.init(title: "Done", style: .done, target: self, action: #selector(onDoneButtonTapped))]
        self.view.addSubview(toolBar)
    }
    

    On Done button you can remove toolBar as well as PickerView.

    @objc func onDoneButtonTapped() {
        toolBar.removeFromSuperview()
        picker.removeFromSuperview()
    }
    

    Delegate methods of UIPickerView

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
        
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return YOUR_DATA_ARRAY.COUNT
    }
        
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return YOUR_DATA_ARRAY[row]
    }
        
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        print(YOUR_DATA_ARRAY[row])
    }