UITextField的resignFirstResponder无法正常工作self.view.endEditing()

时间:2017-04-05 13:20:45

标签: ios iphone swift3 uitextfield resignfirstresponder

我面对一个荒谬的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.
    }


}

截图

enter image description here

4 个答案:

答案 0 :(得分:12)

试试这个

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

 }

答案 1 :(得分:5)

删除1 2 5 6 8 50 方法,将其替换为textFieldDidBeginEditing

textFieldShouldBeginEditing

答案 2 :(得分:0)

迅速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
    }

答案 3 :(得分:0)

运行textfield.resignFirstResponder()

所以一切都会像

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