解决了!代码更新和工作!非常感谢Alex Zimin!
一个简短的问题:在注册过程中,我想要求用户从值列表中选择一个值.
是否使用视图控制器添加所有文本字段和值为UIPickerView的正确方法?由于选择器视图在文本区域之间需要如此大的空间,我不知道在这种情况下最好的做法是什么?
这是我的代码到目前为止
class RegisterViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource{ @IBOutlet weak var gradeTextField: UITextField! var gradePicker: UIPickerView! let gradePickerValues = ["5. Klasse","6. Klasse","7. Klasse"] func numberOfComponentsInPickerView(pickerView: UIPickerView!) -> Int{ return 1 } func pickerView(pickerView: UIPickerView,numberOfRowsInComponent component: Int) -> Int{ return gradePickerValues.count } func pickerView(pickerView: UIPickerView,titleForRow row: Int,forComponent component: Int) -> String! { return gradePickerValues[row] } func pickerView(pickerView: UIPickerView!,didSelectRow row: Int,inComponent component: Int){ gradeTextField.text = gradePickerValues[row] self.view.endEditing(true) } override func viewDidLoad() { super.viewDidLoad() statusMessageLabel.hidden = true gradePicker = UIPickerView() gradePicker.dataSource = self gradePicker.delegate = self gradeTextField.inputView = gradePicker gradeTextField.text = gradePickerValues[0] }
选择器视图在开头隐藏,只有当我选择文本字段时才出现,这到目前为止还不错…但是选择器视图是空的…
解决方法
这取决于控制器的外观.如果每个屏幕只有一个选择动作,最好将表视图放在其上,选定的行将是当前选择.
如果屏幕有多个字段,该用户应该采取行动,那么在我看来,最好把标签按钮放在它上方,当用户按下这个按钮时,您只需从屏幕底部显示“Picker View”.当用户在“Picker View”中选择任何行时,您可以更改标签文本,但不要隐藏选择器本身,所以应该按上述“Done”按钮完成.
希望这可以帮助.
UPD:
你的问题,因为你只是忘了设置UIPickerView的dataSource属性
只要做:gradePicker.dataSource = self在viewDidLoad()
不要忘了在这里实现协议:class RegisterViewController:UIViewController,UIPickerViewDataSource
UPD 2:
终于做到了如果您在textFiled的inputView中添加UIPickerView,那么它不应该在IB中.所以你可以从故事板(或.xib,如果你使用它)删除它.
然后更改代码就是这样的:
class RegisterViewController: UIViewController,UIPickerViewDataSource { @IBOutlet weak var gradeTextField: UITextField! var gradePicker: UIPickerView! let gradePickerValues = ["5. Klasse","7. Klasse"] func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{ return 1 } func pickerView(pickerView: UIPickerView,numberOfRowsInComponent component: Int) -> Int{ return gradePickerValues.count } func pickerView(pickerView: UIPickerView,forComponent component: Int) -> String! { return gradePickerValues[row] } func pickerView(pickerView: UIPickerView!,inComponent component: Int){ gradeTextField.text = gradePickerValues[row] self.view.endEditing(true) } override func viewDidLoad() { super.viewDidLoad() gradePicker = UIPickerView() gradePicker.dataSource = self gradePicker.delegate = self gradeTextField.inputView = gradePicker gradeTextField.text = gradePickerValues[0] } }