小编典典

显示UIPickerView文本字段处于选中状态,选中后隐藏

swift

我正在尝试创建一个文本框,当选中它时,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])"

}

阅读 433

收藏
2020-07-07

共1个答案

小编典典

如果我了解您的问题,那么您需要:

  1. 具有UITextField该显示文本选择的
  2. 用户单击时打开选择器 UITextField
  3. 选择一个项目(在选择器中)时,关闭选择器,然后在 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显示选择器中时UITextField被选择
  • 选择项目后隐藏选择器,然后设置 UITextField
  • 在选择UITextField任何项目时将选择器的第一行设置为
2020-07-07