Wild Goat
Wild Goat

Reputation: 3579

IOS8. Close UIPickerView on selection click swift

I do have a UIPicker view populated with selection options. I select on of them and click but UIViewPicker doesn't close. How do I close it or at least fire the event so that I could hide it programatically?

I looked at UIPickerViewDelegate but haven't found any suitable method which would execute not on item selection but only when I click selected item.

Thanks for any help!

Upvotes: 2

Views: 9457

Answers (3)

Gabriel J. S. Oliveira
Gabriel J. S. Oliveira

Reputation: 104

In didSelectRow method just add this line at the end of interaction:

self.view.endEditing(true)

Upvotes: 2

BadLuckJ
BadLuckJ

Reputation: 75

You could make the picker visible once the user clicks in the text field using the textFieldDidBeginEditing function, then hide using the didSelectRow function...

    func textFieldDidBeginEditing(textField: UITextField) {

        myPicker.hidden = false

    }

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        myTextField.text = myPicker[row]
        myPicker.hidden = true

    }

I also recommend you add the touchesBegan function to hide it if the user touches any part of the screen outside of the picker view.

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

         myPicker.hidden = true

    }

I'm of course assuming you've done all required dataSource and delegate linking and functions for the UIPickerView...

Upvotes: 1

Ramesh
Ramesh

Reputation: 617

use the delegate method of UIPickerView like bellow..

  • (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {

    yourTextField.text = [yourArray objectAtIndex:row];
    thePickerView.hidden = YES;
    

    }

Update

you could add a UITapGestureRecognizer to the UIPickerView:

UITapGestureRecognizer *tapGR = [UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pickerViewTapped]; [pickerView addGestureRecognizer:tapGR];

And then:

  • (void)pickerViewTapped { // dismiss the picker. }

Upvotes: 0

Related Questions