显示UIPickerView文本字段被选中,然后在选中后隐藏
我正在尝试创build一个文本框,当它被选中时,一个UIPickerView打开,并从中进行select。 一旦选定,UIPickerView隐藏,选定的项目显示在文本框中。 我尝试了不同的代码,我在网上find,但我不能得到它的工作。 如果有人可以为此提出一个完整的代码,或者告诉我在代码中我做了什么错误,那就太棒了。 非常感谢。
这是我的代码:
@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
时打开一个select器 - select一个项目(在选取器中)时closures选取器,并将其设置在UITextField中
这是完整的代码来pipe理它,你只需要链接你的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
在selectUITextFieldDelegate
时显示选取器 - select一个项目后隐藏select器,然后设置
UITextField
- select任何项目时,将
UITextField
中的选取器的第一行设置
// pressing the button again would hide the uipickerview. when pressed the first time, update the button's label to "done" , "hide" or whatever suits u! @IBAction func propertyTypeButtonPressed(sender: UIButton)/* the name of your button's action*/ { count++; //declare it first ViewContainigPickerView.hidden = false self.view.endEditing(true) if (count == 2) { ViewContainingPickerView.hidden = true /* if you placed your picker on a separate view for simplicity*/ count = 0; } }
如何在你resSeFirstResponder的didSelectRow方法?
func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int) { textfieldBizCat.text = bizCat[row] pickerBizCat.resignFirstResponder() }