My code bellow is a uitextfiled that uses a picker view to display a and b. All I want to do is have the is have the same picker view appear for all of the textfields using outlet collection. Textfield is the single textField and mutlipleTextifeld is the outlet collection the one I want to use. I I just want to replace textField with mutlipleTextifield.
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
let picker = UIPickerView()
let country = ["a","b"]
@IBOutlet var mutlipleTextifeld: [UITextField]!
override func viewDidLoad() {
super.viewDidLoad()
for textFieldObject in mutlipleTextifeld
{
textFieldObject.inputView = picker
}}
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return country.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return country[row]
}
public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
mutlipleTextifeld.text = country[row]
self.view.endEditing(false)
}}
First set the dataSource
and Delegate
of the pickerView
to self
ie the ViewController
class. As I see you haven't. So your viewDidLoad()
would be somewhat like this:
override func viewDidLoad() {
super.viewDidLoad()
picker.delegate = self
picker.dataSource = self
print (textFields.count)
for textFieldObject in textFields
{
textFieldObject.inputView = picker
}
}
And your func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
delegate
would be like this:
public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
for textField in textFields {
if textField.isEditing {
textField.text = country[row]
}
}
self.view.endEditing(false)
}
Output