ResignFirstResponder from a function outside the view controller

698 views Asked by At

I am currently working with UITextField with an inputview - UIPickerView and I have added a done button to the top the UIPickerView. I can close the picker view with the done button by resigning the first responder of the textfield from the view controller class using

let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.dismissPickerView))

func dismissPickerView() {
    myTextField.resignFirstResponder
}

The problem is that I want to call a function out side the viewController class that resigns the first responder on the myTextField like below

func doneButton (viewcontroller: UIViewController,textfield:UITextField) {   
    let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(textfield.resignFirstResponder))
} 

so I can use it for multiple picker views but I don't know how to implement the SELECTOR OF THE "func doneButton"

ANY FEEDBack will HELP

1

There are 1 answers

2
Atif On

You create a helper singleton class, which will be observing to UITextFieldTextDidBeginEditingNotification,UITextFieldTextDidEndEditingNotification. Store/Clear reference of text field or any other first-responder object when notification is fired

Add a static or object method to the singleton class which will be resigning first responder on the object previously stored from notification

Swift 3.0

class KeyBoardHelper {

var firstResponder:UIView?

static let sharedInstance = KeyBoardHelper()

static func initializedInstance()
{
    _ = sharedInstance
}

init()
{
    print("Start listning for keyboard event")

    NotificationCenter.default.addObserver(self, selector: #selector(KeyBoardHelper.keyboardWillShow(notification:)), name: NSNotification.Name.UITextFieldTextDidBeginEditing, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(KeyBoardHelper.keyboardWillHide(notification:)), name: NSNotification.Name.UITextViewTextDidEndEditing, object: nil)
}

@objc func keyboardWillShow(notification:Notification)
{
    firstResponder = notification.object as? UIView
}

@objc func keyboardWillHide(notification:Notification)
{
    firstResponder = nil
}


static func resignKeyboard()
{
    KeyBoardHelper.sharedInstance.firstResponder?.resignFirstResponder()
}

@objc func dismissKeyboard()
{
    firstResponder?.resignFirstResponder()
}

static func resignBarButton() -> UIBarButtonItem
{
    let barButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: KeyBoardHelper.sharedInstance, action: #selector(KeyBoardHelper.dismissKeyboard))
    return barButton
}

}