I have found this video where was shown way for adding picker views with fields to the app. I have added three fields:
@IBOutlet weak var position: UITextField!
@IBOutlet weak var emplFilter: UITextField!
@IBOutlet weak var locFilter: UITextField!
and also variables which represents current text field and picker:
var currentTextField = UITextField()
var currentPicker = UIPickerView()
and also added implementations:
UITableViewDelegate, UITableViewDataSource,UITextFieldDelegate,UIPickerViewDelegate,UIPickerViewDataSource
Added all methods:
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if currentTextField == locFilter{
return location.count
}else if currentTextField == test{
return proffestion.count
}else if currentTextField == emplFilter{
return employer.count
}else{
return 0
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if currentTextField == locFilter{
return location[row].name
}else if currentTextField == test{
return proffestion[row].name
}else if currentTextField == emplFilter{
return employer[row].name
}else{
return ""
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if currentTextField == locFilter{
locFilter.text = location[row].name
filters!["location"] = location[row].id
self.view.endEditing(true)
}else if currentTextField == test{
filters!["prof"] = proffestion[row].id
test.text = proffestion[row].name
self.view.endEditing(true)
}else if currentTextField == emplFilter{
emplFilter.text = employer[row].name
filters!["employer"] = "\(String(describing: employer[row].id))"
self.view.endEditing(true)
}
}
func textFieldDidBeginEditing(_ textField: UITextField) {
self.currentPicker.delegate = self
self.currentPicker.dataSource = self
print("click")
currentTextField = textField
if currentTextField == locFilter{
currentTextField.inputView = currentPicker
}else if currentTextField == test{
currentTextField.inputView = currentPicker
}else if currentTextField == emplFilter{
currentTextField.inputView = currentPicker
}
self.currentPicker.delegate = self
self.currentPicker.dataSource = self
}
and here I have a problem - when I click on position
field I don't see any output in logs. I can't understand why it happens, I tried to add another field but it didn't change the situation. I tried to use another array but I also didn't see any picker view. I tried to look for any possible solution in the Internet, but I didn't succeed in it :(
Setting the delegate
of position
UITextField
should fix the issue.
position.delegate = self
I would also like to point out that you don't need to repetitively set delegate
and dataSource
of UIPickerView
everytime a text field begins editing.