在Swift 4中使用UIPickerView时如何隐藏键盘?

时间:2019-01-01 16:18:53

标签: ios swift uipickerview

我的代码有问题,因为我使用的是UIPickerView,但是当我们从一个文本字段切换到另一个文本字段时,尽管下面的代码没有隐藏键盘。

我很高兴能有人帮助我。

(我已经对此错误进行了研究,但是我所看到的代码都没有解决我的问题)

@IBOutlet weak var colorPickerView: UIPickerView!

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

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


func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    self.view.endEditing(true)
    return list[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    self.colorTxtField.text! = self.list[row]
    self.colorPickerView.isHidden = true
}


func textFieldDidBeginEditing(_ textField: UITextField) {
    if textField == self.colorTxtField {
        self.colorPickerView.isHidden = false
        textField.endEditing(true)

    }
}

我很高兴有人可以帮助我。

2 个答案:

答案 0 :(得分:0)

我认为您显示的PickerView错误。您,不必写

  

func textFieldDidBeginEditing(_ textField:UITextField)

代替显示选择器,只需在您的viewDidLoad

中写此行
self.colorTxtField.inputView = self.colorPickerView

答案 1 :(得分:0)

在一段时间内遇到了同样的问题,但是运气并不好。但是我从@D得到了一些解决方法。上面的Mika(谢谢!)评论是要实现textFieldShouldBeginEditing

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    self.view.endEditing(true)
    //or:
    self.view.resignFirstResponder()
    return true
}

该解决方案在一定程度上可以解决问题,因为它隐藏了停留在上一个文本字段之外的键盘,但是它无法启用立即的下一个点击字段编辑-因此,事实上的用户必须轻按两次。这样更好,那就没有了