键盘有时会在iOS的文本字段选择器视图中显示

时间:2019-02-12 12:34:14

标签: ios swift keyboard uitextfield uipickerview

我有一个文本字段,点击该文本字段将显示一个UIPickerView。我将其添加为文本字段的inputView。有时,当我点击文本字段时,它显示键盘而不是选择器视图。我还添加了一个自定义类,该类也继承了UITextField

override func viewDidLoad() {
    // ...
    monthTextField.addTarget(self, action: #selector(monthTextFieldDidTap), for: UIControl.Event.touchDown)
}


@objc func monthTextFieldDidTap(textField: UITextField) {
    activePickerType = PickerType.month
    viewDatePicker(textField)
}

@objc func yearTextFieldDidTap(textField: UITextField) {
    activePickerType = PickerType.year
    viewDatePicker(textField)
}

func viewDatePicker(_ textField: UITextField) {
    self.datePicker = UIPickerView.init(frame: CGRect.init(x: 0, y: 0, width: self.navigationController!.view.frame.size.width, height: 216))
    self.datePicker.delegate = self
    self.datePicker.dataSource = self
    textField.inputView = self.datePicker
    // ...
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    if (textField == monthTextField) {
        return true
    }
    return false
}

UITextField的自定义子类:

class PickerTextField: UITextField {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func caretRect(for position: UITextPosition) -> CGRect {
        return CGRect.zero
    }

    func selectionRects(for range: UITextRange) -> [Any] {
        return []
    }

    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        UIMenuController.shared.isMenuVisible = false
        self.resignFirstResponder()
        return false
    }
}

如何确保在点击UITextField时不显示键盘并始终显示UIPickerView

2 个答案:

答案 0 :(得分:1)

将这些行放置在viewDidLoad中,而不是monthTextFieldDidTap

self.datePicker = UIPickerView.init(frame: CGRect.init(x: 0, y: 0, width: self.navigationController!.view.frame.size.width, height: 216))
self.datePicker.delegate = self
self.datePicker.dataSource = self
monthTextField.inputView = self.datePicker



func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
if (textField == monthTextField) {
    activePickerType = PickerType.month
    viewDatePicker(textField)

}
return true

}

答案 1 :(得分:0)

在monthTextFieldDidTap(textField:UITextField)函数中添加self.view.endEditing()行,如下所示:

@objc func monthTextFieldDidTap(textField: UITextField) {
    self.view.endEditing(true)
    monthTextField.tintColor = UIColor.clear    //optional to use. It just removes cursor blinking on picker Textfield
    self.datePicker = UIPickerView.init(frame: CGRect.init(x: 0, y: 0, width: self.navigationController!.view.frame.size.width, height: 216))
    self.datePicker.delegate = self
    self.datePicker.dataSource = self
    textField.inputView = self.datePicker
    // ...
}