Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm facing a ridiculous problem for textField, I have two textfield, namely tfA and tfB, I have set delegates and all for those textfields, what i wanted is, if I click on tfA then it should print something, and it is printing and if I click tfB it should appear the keyboard, well it is working well too, but when I click again to tfA then it should print something and keyboard should dismiss according to the condition given there, But keyboard is not dismissing there also self.view.endEditing(true) is not working here . Code is given below with screen shot, what I'm doing wrong here?

CODE: 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.
    }


}

Screenshots

enter image description here

like image 220
Abhishek Mitra Avatar asked Apr 05 '17 13:04

Abhishek Mitra


People also ask

What is endEditing in Swift?

Causes the view (or one of its embedded text fields) to resign the first responder status.

How do you dismiss a keyboard in Swift?

Via Tap Gesture This is the quickest way to implement keyboard dismissal. Just set a Tap gesture on the main View and hook that gesture with a function which calls view. endEditing .

What is resignFirstResponder Swift?

resignFirstResponder()Notifies this object that it has been asked to relinquish its status as first responder in its window. iOS 2.0+ iPadOS 2.0+ Mac Catalyst 13.0+ tvOS 9.0+


1 Answers

Try this

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

 }
like image 69
RajeshKumar R Avatar answered Sep 30 '22 14:09

RajeshKumar R