Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically implementing a UIPickerView when user taps UITextfield

I am currently working on a small project and i have a viewController that has 4 textFields which 3 work ok. They take String objects. However, the 4th textField is supposed to bring up a UIPickerView with 4 selectable items.

So far this is what i have in my controller that implements this:

     @IBOutlet var pickerTextfield: UITextField!
     @IBOutlet var itemPicker: UIPickerView! = UIPickerView()  

The pickerTextfield is the UITextField object that is the 4th field. The itemPicker is an unlinked UIPickerView that i want to create programatically.

Right below these properties, i have an array of items for the UIPickerView object:

var seasonalItems = ["Spring", "Summer", "Fall", "Winter"]

In my viewDidLoad method i have this as follow:

    itemPicker.hidden = true;
    pickerTextfield.text = seasonalItems[0]

    pickerTextfield.delegate = self

And the rest of the implementation:

// Below these lines is the implementation of the Picker

func numberOfComponentsInPickerView(pickerView: UIPickerView!) -> Int{
    return 1
}

// returns the # of rows in each component..
func pickerView(pickerView: UIPickerView!, numberOfRowsInComponent component: Int) -> Int{
    return seasonalItems.count
}

func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String! {
    return seasonalItems[row]
}

func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int)
{
    pickerTextfield.text = seasonalItems[row]
    itemPicker.hidden = true;
}

func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
    itemPicker.hidden = false
    return false
}

So the end result from this is when i tap the pickerTextfield object in the app, it shows the first item of the array (Spring) but in text within the UITextField object but it does not show the UIPickerView object with the other selectable items where i could select one and then hide it when selected.

My question is, where or what am i doing wrong here? i been trying to figure this out on my own but i do not seem to get good clear examples with Swift and storyboards. I much rather not drag a UIPickerView in the storyboard but rather the way i attempted to implement. Thanks

like image 429
Amit Avatar asked Sep 29 '22 10:09

Amit


1 Answers

You can give UIPickerView as inputView for your TextField in which you want to show picker view. You also do not need to initially hide picker view in this case.

pickerTextfield.inputView = itemPicker

When you use UIPickerView as inputView of any UITextField then when you tap on the TextField instead of default keypad PickerView will show.

like image 68
Yuvrajsinh Avatar answered Oct 06 '22 19:10

Yuvrajsinh