我正在尝试在PickerView中显示Blood类型,但由于某种原因,选项仅显示为问号!
这是我的代码:
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
}
}
以下是显示内容的屏幕截图:
我正在学习本教程:http://sourcefreeze.com/ios-uipickerview-example-using-swift/
提前致谢。
答案 0 :(得分:5)
你的功能titleForRow
应该是这样的:
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?. You forgot a '_' before pickerView:
答案 1 :(得分:0)
而不是
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return pickerDataSource[row]
}
给
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerDataSource[row]
}
答案 2 :(得分:0)
快捷键4
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerDataSource[row]
}