This code can close the keyboard when the "Home" button is pressed, and return it when the application is restarted. You need to configure the UITextFields delegate to a controller of the form:
class ViewController: UIViewController, UITextFieldDelegate { private var _textField: UITextField! private var _isFirstResponder: Bool! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. NSNotificationCenter.defaultCenter().addObserver(self, selector: "didBecomeActiveNotification:", name: UIApplicationDidBecomeActiveNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "willResignActiveNotification:", name: UIApplicationWillResignActiveNotification, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func didBecomeActiveNotification(nofication: NSNotification) { if _isFirstResponder? == true { _textField?.becomeFirstResponder() } } func willResignActiveNotification(nofication: NSNotification) { if _textField?.isFirstResponder() == true { _isFirstResponder = true _textField?.resignFirstResponder() } else { _isFirstResponder = false } } func textFieldShouldBeginEditing(textField: UITextField) -> Bool { _textField = textField return true } }
source share