UITableView and UIView with keyboardWillShow
I have this UITableView that almost fills my entire UIViewController, and I have a UIView at the bottom that contains a button and a textfield.
When I click the textfield, I want the UIView and tableview to push up, so that the UIView is just on top of the keyboard.
- UIView:
- UITextField
- UIButton
I've tried multiple suggestions on on here, but none seem to work in my situation.
Step 1:
Make an outlet of bottom constraint of UIView
Step 2:
Add observer for keyboard show and hide and then change constraint constant according to keyboard height..
//**In viewDidLoad method**
// register for keyboard notifications
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
// register for keyboard notifications
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
Step 2 in Swift 5:
//**In viewDidLoad method**
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
Step 3:
Manage constraints as keyboard show and hide notification like below
- (void)keyboardWillShow:(NSNotification *)notification
{
NSDictionary* userInfo = [notification userInfo];
// get the size of the keyboard
CGSize keyboardSize = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
CGSize keyboardSizeNew = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
_bottomConstraintofView.constant = keyboardSizeNew.height;
[UIView animateWithDuration:0.2
animations:^{
[self.view layoutIfNeeded]; // Called on parent view
}];
}
- (void)keyboardWillHide:(NSNotification *)notification
{
_bottomConstraintofView.constant = 0;
[UIView animateWithDuration:0.2
animations:^{
[self.view layoutIfNeeded];
}];
}
Solution in Swift
func keyboardWillShow(notification: NSNotification){
let userInfo:NSDictionary = notification.userInfo!
let keyboardSize:CGSize = userInfo.objectForKey(UIKeyboardFrameBeginUserInfoKey)!.CGRectValue().size
let keyboardSizeNow:CGSize = userInfo.objectForKey(UIKeyboardFrameEndUserInfoKey)!.CGRectValue().size
self.bottomConstraintofView.constant = keyboardSizeNow.height
UIView.animateWithDuration(0.2) {
self.view.layoutIfNeeded()
}
}
func keyboardWillHide(notification: NSNotification){
bottomConstraintofView.constant = 0
UIView.animateWithDuration(0.2) {
self.view.layoutIfNeeded()
}
}