我正在尝试创建一个文本框,当选中它时,UIPickerView将打开,并提供可供选择的选项。选择后,UIPickerView将隐藏,并且所选项目将显示在文本框中。我尝试了在网上找到的不同代码,但是无法正常工作。如果有人可以为此建议完整的代码,或者告诉我我在代码中做错了什么,那真是太棒了。非常感谢。
这是我的代码:
@IBOutlet var textfieldBizCat: UITextField! @IBOutlet var pickerBizCat: UIPickerView! = UIPickerView() var bizCat = ["Cat One", "Cat Two", "Cat Three"] override func viewDidLoad() { super.viewDidLoad() var bizCatCount = bizCat.count self.textfieldBizCat.inputView = pickerView } // returns the number of 'columns' to display. func numberOfComponentsInPickerView(pickerView: UIPickerView!) -> Int{ return 1 } // returns the # of rows in each component.. func pickerView(pickerView: UIPickerView!, numberOfRowsInComponent component: Int) -> Int{ return bizCat.count } func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String! { return bizCat[row] } func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int) { textfieldBizCat.text = "\(bizCat[row])" }
如果我了解您的问题,那么您需要:
UITextField
这是完整的代码来管理它,您只需链接您的代理UITextField:
@IBOutlet var textfieldBizCat: UITextField! @IBOutlet var pickerBizCat: UIPickerView! = UIPickerView() var bizCat = ["Cat One", "Cat Two", "Cat Three"] override func viewDidLoad() { super.viewDidLoad() pickerBizCat.hidden = true; textfieldBizCat.text = bizCat[0] } // returns the number of 'columns' to display. func numberOfComponentsInPickerView(pickerView: UIPickerView!) -> Int{ return 1 } // returns the # of rows in each component.. func pickerView(pickerView: UIPickerView!, numberOfRowsInComponent component: Int) -> Int{ return bizCat.count } func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String! { return bizCat[row] } func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int) { textfieldBizCat.text = bizCat[row] pickerBizCat.hidden = true; } func textFieldShouldBeginEditing(textField: UITextField) -> Bool { pickerBizCat.hidden = false return false }
我对您的代码所做的更改:
UITextFieldDelegate