skip to Main Content

I am using UITextField hosted inside UIScrollView and using keyboard notification to adjust content size, right now when scrollview scrolls to textfield the padding between keyboard and textfield is too small. Is there anyway I can customise padding??

3

Answers


  1. You can use IQKeyboardManager for automatically provide padding and without any trouble of scrollView with single Line of code. You can install it via CocoaPods or Manually.

    Login or Signup to reply.
  2. add bottom constraint outlet of Scroll View( this must be the bottom constraint of last textfield from bottom).
    and in that view controller add the following line of code.

        fileprivate func addKeyBoardNotifications() {
            NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
            NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
        }
        
        deinit {
            NotificationCenter.default.removeObserver(self)
        }
        
        @objc func keyboardWillShow(notification: NSNotification) {
            if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
                UIView.animate(withDuration: 0.1, animations: { () -> Void in
    //                self.view.frame.origin.y -= keyboardSize.height
                    self.scrollViewBottomAnchor.constant = -keyboardSize.height
                    self.view.layoutIfNeeded()
                })
            }
        }
    
        @objc func keyboardWillHide(notification: NSNotification) {
            if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
                UIView.animate(withDuration: 0.1, animations: { () -> Void in
                    self.scrollViewBottomAnchor.constant = 0
                    self.view.layoutIfNeeded()
                })
            }
        }
    
    Login or Signup to reply.
  3. Set the contentInset of the UIScrollView

    scrollView.contentInset = .init(top: 0, left: 0, bottom: 15, right: 0)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search