首页 > 解决方案 > 我的键盘不会切换:endEditing 和 resignFirstResponder 都不起作用

问题描述

我正在使用文本字段,并且文本字段所在的视图是由 UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "nickNameInput") as! PopupViewController.

它是一个 PopupViewController。

问题是当我调用 textField.resignFirstResponder()or 时self.view.endEditing(true),它们都不起作用......

我很难过。有人可以帮帮我吗?

    import UIKit

    class PopupViewController: UIViewController, UITextFieldDelegate{
    @IBOutlet weak var editingEndBtn: UIButton!
    @IBOutlet weak var textField: UITextField!
    var inputString = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        let blurEffect = UIBlurEffect(style: .extraLight)
        let blurView = UIVisualEffectView(effect: blurEffect)
        view.insertSubview(blurView, at: 0)

        textField.delegate = self
        editingEndBtn.isEnabled = false
    }



    func textFieldDidBeginEditing(_ textField: UITextField) {    //delegate method
    }

    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {  //delegate method
        inputString = textField.text!
        //print(inputString)
        if (inputString != ""){
            editingEndBtn.isEnabled = true
        }

        textField.resignFirstResponder()
         self.view.endEditing(true)
        return false
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {   //delegate method
       textField.resignFirstResponder()
        print("return is pushed")
        toggleKeyboard()
        return true
    }


}

标签: iosswifttextfield

解决方案


问题就在这里

func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {   
    return false // this prevents it
}

您需要删除此方法或根据文本进行逻辑处理,而无需false返回

func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
    inputString = textField.text! 
    return  inputString != ""
}

推荐阅读