NinjaDeveloper NinjaDeveloper - 2 months ago 8
Swift Question

Picker View is show character "?" instead of item name?

I have problem with hospital ViewPicker. when the user click on text field hospitalName to select hospital name from viewPicker the item is show character "?" instead of item name I have attach Image
Note I use same logic for location text field

enter image description here

class VisitsViewController: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate,UITextFieldDelegate, UIViewControllerTransitioningDelegate {

//MARK -
override func viewDidLoad() {
super.viewDidLoad()
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(BrnViewController.dismissKeybored)))
self.pickerLocation.dataSource = self
self.pickerLocation.delegate = self
self.pickerLocation.tag = 1
self.pickerHospital.dataSource = self
self.pickerHospital.dataSource = self
self.pickerHospital.tag = 2

visitLocationTextField.inputView = pickerLocation
self.visitLocationTextField.delegate = self
hospitalNameTextField.inputView = pickerHospital
self.hospitalNameTextField.delegate = self
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

// MARK: - Picker View
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView.tag == 1 {
return pickerDataVisitLocation.count
}
else{
return pickerDataHospitalName.count
}
}

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){
if pickerView.tag == 1{
visitLocationTextField.text = pickerDataVisitLocation[row]
}
else{
HospitalNameTextField.text = pickerDataHospitalName[row]
}
}

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int)-> String? {
if pickerView.tag == 1{
return pickerDataVisitLocation[row]
}
else{
return pickerDataHospitalName[row]
}
}
//MARK: - @IBOutlet
@IBOutlet weak var visitLocationTextField: UITextField!
@IBOutlet weak var hospitalNameTextField: UITextField!

//MARK: - variables
var pickerDataVisitLocation = [" ","Home","Hospital","Other"]
var pickerDataHospitalName = [" ","test1","test2","test3"]
var pickerLocation = UIPickerView()
var pickerHospital = UIPickerView()
}

Answer

You haven't set pickerHospital delegate. Replicated self.pickerHospital.dataSource = self two times. You should have wrote:

self.pickerHospital.dataSource = self
self.pickerHospital.delegate = self