Deutro
Deutro

Reputation: 3313

How to make all textfields close keyboard on return?

I am currently learning Swift and have some TextFields in my application. Now I want the user to close the keyboard if he presses the return key in a TextField or taps anywhere on the screen.

Currently I add the same code in all of my controllers which I do not really like. Is there a way to make all controllers / TextFields to behave the way I described above.

Closing the keyboard with return:

func textFieldShouldReturn(textField: UITextField!) -> Bool {
    textField.resignFirstResponder()
    return true
}

Closing the keyboard on tapping on the screen:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    self.view.endEditing(true)
}

This I want to have in all of my Controllers without copying it each time.

Upvotes: 2

Views: 122

Answers (1)

Christian
Christian

Reputation: 22343

You can subclass the UITextField and create your own TextField. Than if you add a UITextField to your Storyboard, just set the class to your textfield class in the identity inspector.

class YourTextField : UITextField, UITextFieldDelegate {
    override init(){
        super.init()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.delegate = self
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.delegate = self
    }

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}

Upvotes: 3

Related Questions