Search code examples
iosswiftkeyboarduitextfieldscrollviewer

How to make scrollview up to keyboard height according to iPhone sizes in swift


I have added scrollView top,left,right,bottom 0. in scrollView i have added viewinScrollview with height 550, in this view i have added fieldsContainerView. like below

storyboard view hierarchy img

if i run project in iPhone8 then design looks good, but if i run in iPhone 11 pro i am seeing unnecessary scrollview. i have given scrollview color is green and viewinScrollview color is white.

in iPhone 11 pro i am getting like below, the green space is scroll view i dont want that space after keyboard iPhone 11 pro

this is iPhone8 simulator iPhone8 i need like this in all iPhone sizes.

here is the code:

 override func viewDidLoad() {
      super.viewDidLoad()

      NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow), name: UIResponder.keyboardDidShowNotification, object: nil)
      NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHide), name: UIResponder.keyboardDidHideNotification, object: nil)

  }

  @objc func keyboardDidShow(notification: NSNotification) {
      let info = notification.userInfo
      let keyBoardSize = info![UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
      scrolView.contentInset = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyBoardSize.height, right: 0.0)
      scrolView.scrollIndicatorInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyBoardSize.height, right: 0.0)
  }

  @objc func keyboardDidHide(notification: NSNotification) {
      scrolView.contentInset = UIEdgeInsets.zero
      scrolView.scrollIndicatorInsets = UIEdgeInsets.zero
  }

please help me to remove green color space in all iPhone sizes.


Solution

  • Remove background colour of scrollview in your storyboard .

    You can follow my approach for more clarifications .

    moving-keyboard-when-editing-multiple-textfields-with-constraints-swift