Reputation: 384
I found a custom UIPickerView (https://github.com/bendodson/MonthYearPickerView-Swift) to select only Month and Day. It pops up fine however I don't know how to populate the text field after I press "done". I found a few examples online which don't appear to be working for me.
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(donePressed))
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelPressed))
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.default
toolBar.isTranslucent = true
toolBar.tintColor = themeColor1()
toolBar.sizeToFit()
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
let StartDatePicker = MonthYearPickerView()
StartDate.inputView = StartDatePicker
StartDate.inputAccessoryView = toolBar
}
func donePressed() {
StartDate.text = ???
self.view.endEditing(true)
}
func cancelPressed() {
self.view.endEditing(true)
}
Upvotes: 0
Views: 1332
Reputation: 611
you need to add a delegate of picker view ..
pickerView.delegate = self
then implement its method named as
func pickerView(pickerView: UIPickerView!, numberOfRowsInComponent component: Int) -> Int {
return yourList.count
}
func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String! {
return yourList[row]
}
Now, if you want picker view to appear on touching TextField you need to do this
textField.inputView = pickerView
Also implement
func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int) {
yourTextfield.text = yourList[row]
}
so that when you select any row in a pickerView, the title of that row will be assign to your text field ..
Upvotes: 1
Reputation: 2524
You need to use the delegate method for picker view, didSelectRow. I have a similar picker view and I have multiple textviews. So in the method I check to see who is the first responder and then I set that text view to a string that is equal to the picker value.
Make sure your view controller conforms to UIPickerViewDelegate and datasource which it seems you have already done.
In the function make an if statement: if (yourTextView.isFirstResponder)
create a string to hold the picker value: myString = pickerView array object at index
assign that string to your textview: StartDate.text = myString
This is only pseudo code, because I wrote all my methods in Objective C. Make a comment if you need further assistance.
Upvotes: 1