问题
I'm trying to display Blood type in PickerView, but for some reason the choices are displayed as question marks only !
Here is my code:
class RegisterViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
//Methods for PickerViewDataSource
@available(iOS 2.0, *)
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerDataSource.count;
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return pickerDataSource[row]
}
@IBOutlet weak var selectedDate: UILabel!
@IBOutlet weak var birthDatePicker: UIDatePicker!
@IBOutlet weak var mobileNumberField: UITextField!
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var nameField: UITextField!
@IBOutlet weak var bloodTypePicker: UIPickerView!
@IBOutlet weak var selectedType: UILabel!
let pickerDataSource = ["Group A", "Group B", "Group AB", "Group O"];
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
super.viewDidLoad()
self.bloodTypePicker.dataSource = self;
self.bloodTypePicker.delegate = self;
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
if(row == 0)
{
self.selectedType.text = "Group A"
}
else if(row == 1)
{
self.selectedType.text = "Group B"
}
else if(row == 2)
{
self.selectedType.text = "Group AB"
}
else
{
self.selectedType.text = "Group O"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func datePickerAction(_ sender: Any) {
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
var strDate = dateFormatter.string(from: birthDatePicker.date)
self.selectedDate.text = strDate
}
}
and here is a screenshot of what is displayed:
I was following this tutorial: http://sourcefreeze.com/ios-uipickerview-example-using-swift/
Thanks in advance.
回答1:
Your function titleForRow
should be like this one:
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?. You forgot a '_' before pickerView:
回答2:
instead of this
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return pickerDataSource[row]
}
give
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerDataSource[row]
}
回答3:
Swift 4
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerDataSource[row]
}
来源:https://stackoverflow.com/questions/41041692/uipickerview-display-question-mark