Multiple UIPickerView in the same UIView
Here is Full Source Multiple UIPickerView in the TextField
in Swift 3
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var textFiel1: UITextField!
@IBOutlet weak var textFiel_2: UITextField!
let piker1 = UIPickerView()
let piker2 = UIPickerView()
let country = ["Ban","Ind","PK"]
let number = ["1","2","3"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
piker1.dataSource = self
piker1.delegate = self
piker2.dataSource = self
piker2.delegate = self
piker1.tag = 1
piker2.tag = 2;
textFiel1.inputView = piker1
textFiel_2.inputView = piker2
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == piker1 {
return country.count
} else if pickerView == piker2{
return number.count
}
return 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == piker1 {
return country[row]
} else if pickerView == piker2{
return number[row]
}
return ""
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == piker1 {
textFiel1.text = country[row]
self.view.endEditing(false)
} else if pickerView == piker2{
textFiel_2.text = number[row]
self.view.endEditing(false)
}
}
}
You're comparing instances with tags.
Replace:
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
if pickerView2 == 2 {
return test[row]
} else if pickerView3 == 3{
return test2[row]
}
return ""
}
with:
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
if pickerView2.tag == 2 {
return test[row]
} else if pickerView3.tag == 3 {
return test2[row]
}
return ""
}
Anyway, you don't need to tag your pickers. The pickers come in the datasource and delegate methods. You can compare instances. Something like this:
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
if pickerView2 == pickerView {
return test[row]
}
if pickerView3 == pickerView {
return test2[row]
}
return ""
}
You don't need tags, just use:
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
if pickerView == pickerView1 {
//pickerView1
} else if pickerView == pickerView2{
//pickerView2
}
also don't forget to set delegate in IB or in code:
pickerView1.delegate = self