简体   繁体   中英

Keyboard handling in iOS

I have an issue with my application. I am actually building a login page and I do not find how to handle the keyboard when a text field is active. I have two text fields in a view. In my superView, I have 3 views. One on the bottom, another on the middle and a last on top. The 3 views are embeded in a stack view.

I really want to shrink the stack view, in other words reduce the space between all 3 views only when the keyboard appears and set the size back when the keybaord disappear, like Facebook login page on iOS.

You need to subscribe to keyboard notifications and do this in viewDidLoad

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: .UIKeyboardWillHide, object: nil)

//

@objc func keyboardWillShow(notification: NSNotification) {
   self.stackV.spacing = 10
    UIView.animate(withDuration: 0.3, animations: { () -> Void in
        self.view.layoutIfNeeded()
    })
}

@objc func keyboardWillHide(notification: NSNotification) {
    self.stackV.spacing = // set back to default
    UIView.animate(withDuration: 0.3, animations: { () -> Void in
        self.view.layoutIfNeeded()
    })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM