UITableView and UIView with keyboardWillShow

Step 1:
Make an outlet of bottom constraint of UIView

enter image description here

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()
    }
}

Leave a Comment