UITextField 的 resignFirstResponder 既不工作也不工作 self.view.endEditing()

UITextField's resignFirstResponder is not working neither working self.view.endEditing()

我正面临一个关于 textField 的荒谬问题,我有两个文本字段,即 tfA 和 tfB,我已经为这些文本字段设置了委托和所有内容,我想要的是,如果我点击 tfA,它应该打印一些东西,它正在打印,如果我单击 tfB,它应该会出现键盘,它也运行良好,但是当我再次单击 tfA 时,它应该打印一些东西,键盘应该根据那里给出的条件关闭,但键盘不是解散那里也 self.view.endEditing(true) 在这里不起作用。下面给出了代码和屏幕截图,我在这里做错了什么?

代码:Swift 3

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet weak var tfA: UITextField!
    @IBOutlet weak var tfB: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        tfA.delegate = self
        tfB.delegate = self
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField == tfA{
            print("TFA Clicked")
            textField.resignFirstResponder()
            self.view.endEditing(true)
        }else{
            tfB.becomeFirstResponder()
        }
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()

        return true
    }

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


}

截图

试试这个

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
   if textField == tfA
   {
       tfaAction()
       return false
   }
   else
   {
       return true
   }
}
func tfaAction(){

 }

删除您的 textFieldDidBeginEditing 方法,将其替换为 textFieldShouldBeginEditing:

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
  if textField == tfA{
    print("TFA Clicked")
    self.view.endEditing(true)
    return false
  }else{
    return true
  }
}

Swift 4 请只检查这个 delegate 如果它存在那么它应该 return true

`func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {`


    //MARK:- Textfield Delegates //This is mandatory 
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.view.endEditing(true)
        return true
    }

    //MARK:- This Delegate is option  but if this is exist in your code then return type shoud be true 
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {

        return true
    }

运行 textfield.resignFirstResponder()

所以一切都会像

textfield.resignFirstResponder()
self.view.endEditing(true)