UITextField上的“清除”按钮可关闭键盘,而不是清除文本

时间:2019-08-05 10:02:22

标签: swift uitextfield

我有一些UITextFields,其中一些当键盘显示处于其位置时隐藏了其他UITextFields,因此我将视图向上移动以进行查看。 对于这些位置,清除按钮可以完美地工作。 但是,这些按钮会向上移动,当我按清除按钮时,键盘将关闭而不是清除文本。

我尝试执行以下操作以使清除按钮起作用:

   func textFieldShouldClear(_ textField: UITextField) -> Bool {
        textField.text = ""
        textField.resignFirstResponder()
        return false
    }

但这没用。

这是我用来在键盘出现时向上移动视图的代码:

@objc func keyboardWillShow(notification:Notification) {
        view.frame.origin.y = 0
        view.frame.origin.y -= getKeyboardHeight(notification)
    }

    @objc func keyboardWillHide(notification:Notification) {
        view.frame.origin.y = 0
    }


    func getKeyboardHeight(_ notification:Notification) -> CGFloat {

        let userInfo = notification.userInfo
        let keyboardSize = userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue // of CGRect
        return keyboardSize.cgRectValue.height
    }

    func subscribeToKeyboardNotifications() {

        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
    }

    func unsubscribeFromKeyboardNotifications() {

        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
    }

    func subscribeToKeyboardHideNotifications() {

        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }

    func unsubscribeFromKeyboardHideNotifications() {

        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
    }

0 个答案:

没有答案