How to customize keyboard scrolling in fast 3+ mode

How do you configure scrollview to compensate for the vertical keyboard? Read on ...

Yes, I know that this is some basic information, but I accidentally noticed today that all the answers that I saw on this topic are everywhere found with information, versions and / or use bangs everywhere ... but nothing hard for Swift 3+.

+4
source share
2 answers

Swift 3:

let scrollView = UIScrollView()

Add observers.

override open func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(noti:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(noti:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
}

Add some features to listen to notifications:

//---------------------------------
// MARK: - Notification Center
//---------------------------------

func keyboardWillHide(noti: Notification) {
    let contentInsets = UIEdgeInsets.zero
    scrollView.contentInset = contentInsets
    scrollView.scrollIndicatorInsets = contentInsets
}


func keyboardWillShow(noti: Notification) {

    guard let userInfo = noti.userInfo else { return }
    guard var keyboardFrame: CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue else { return }
    keyboardFrame = self.view.convert(keyboardFrame, from: nil)

    var contentInset:UIEdgeInsets = scrollView.contentInset
    contentInset.bottom = keyboardFrame.size.height
    scrollView.contentInset = contentInset
}

It should be noted that if the deployment target is iOS 9 or higher, you no longer need to remove the observer. See the NotificationCenter docs for more information.

deinit {
    NotificationCenter.default.removeObserver(self)
}
+11

iOS 11 UIKeyboardFrameEndUserInfoKey, UIKeyboardFrameBeginUserInfoKey. @crewshin:

@objc func keyboardWillShow(_ notification: NSNotification) {                
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        scrollView.contentInset.bottom = keyboardSize.height
    }
}

@objc func keyboardWillHide(_ notification: NSNotification) {        
    scrollView.contentInset.bottom = 0
}
+6

Source: https://habr.com/ru/post/1677875/