Search code examples
iosipaduiscrollviewkeyboarduitextview

UIScrollView scroll up on Keyboard


Problem Statement : I have Nib file of UIView contains UIScrollview, In scrollview I have several TextFields and a TextView at the Bottom. What I want is to scroll upward when textfield or Textview starts editing.

What I tried :

In custome Method

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

I am calling this method parent view.

Notification Handling:

func keyboardWasShown(notification: NSNotification)
{
    var userInfo = notification.userInfo!
    var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
    keyboardFrame = self.convert(keyboardFrame, from: nil)

    var contentInset:UIEdgeInsets = self.mainScroll.contentInset
    contentInset.bottom = keyboardFrame.size.height
    self.mainScroll.contentInset = contentInset
}

This is working perfectly for UITextFields, But not working UITextView. Any idea where is the mistake.

PS: I have set the Delegates of UITextField and UITextView as well.

Any help will be much appreciated.


Solution

  • Replace keyboardWasShown function with the below function :

     func keyboardWasShown(notification: NSNotification)
    {
        var userInfo = notification.userInfo!
        var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
        keyboardFrame = self.convert(keyboardFrame, from: nil)
        self.mainScroll.contentOffset = CGPoint(x: 0, y: keyboardFrame.size.height - Any number that fits your need.)
    }
    

    In keyBoardWillHide :

    self.mainScroll.contentOffset = CGPoint(x: 0, y: 0)
    

    Hope it will help. Happy Coding!