当我使用PickerView和textField时隐藏键盘

时间:2017-03-25 13:21:47

标签: ios swift3 xcode8

我想要实现一个简单的应用程序,但我遇到了一些麻烦。我添加了textField和PickerView。当我在textField上选中时,会出现PickerView。但标准键盘也出现了(我不想要它)。当我再次在textField上选项卡时,PickerView不会出现。我怎么能收到这个问题?非常感谢!

这是我的代码:

    import UIKit

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {

    @IBOutlet weak var pickerView1: UIPickerView!
    @IBOutlet weak var textField1: UITextField!

    var age = ["8", "18", "28", "38", "48"]

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return age.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if pickerView == pickerView1 {
        }
        return age[row]
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if pickerView == pickerView1 {
            self.textField1.text = self.age[row]
            self.pickerView1.isHidden = true
        }
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField == self.textField1 {
            self.pickerView1.isHidden = false
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

1 个答案:

答案 0 :(得分:3)

为什么你不尝试这种简单的方法,只需将你的pickerview添加为textfield的输入视图

 textField1.inputView = pickerView1
  

由于您的UIPickerView没有返回按钮,因此我不会直接关闭视图,这就是为什么我建议使用inputAccessoryView属性来显示带有完成按钮的工具栏

  let myToolbar = UIToolbar(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(320), height: CGFloat(44)))
    //should code with variables to support view resizing
    let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self.inputAccessoryViewDidFinish))
    //using default text field delegate method here, here you could call
    //myTextField.resignFirstResponder to dismiss the views
    myToolbar.setItems([doneButton], animated: false)
    lblcurrentText.inputAccessoryView = myToolbar

并将该函数调用为

    func inputAccessoryViewDidFinish() {
    lblcurrentText.resignFirstResponder()
}

同时在您的选择器视图中选择后隐藏文本字段,如

 func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    if pickerView == pickerView1 {
        self.textField1.text = self.age[row]
        self.inputAccessoryViewDidFinish()
    }
}

<强>教程

例如,您可以在here

中获得分步教程