Search code examples
iosswiftpaginationkeyboardscrollview

Swift -How to Paginate when Swiping Down


When loading posts, the most recent post is usually at the top of the screen and as the user swipes up, once the scrollView hits the bottom of the screen older posts shown are using this method

func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {

    let contentOffset = scrollView.contentOffset.y

    let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height

    if maximumOffset - contentOffset <= 40 {

        handlePagination()
    }
}

But when loading messages it's the exact opposite. The most recent message is at the bottom of the screen and as the user swipes down once the scrollView hits the top of the screen older messages are shown.

There are 2 situations to take into account:

1- there is usually a textField or a textView with a sendButton at the bottom of the screen. If the user doesn't touch the textField/ or textView, they can just swipe down and once the scrollView hits the top of the screen handlePagination() will get called to show older messages

2- If the user touches the textView/Field, the keyboard is raised, even if they type some text into the textView/Field they can still swipe down to view older messages

The questions are

1. How can I detect when the user scrolls down so I can call handlePaginate() when the scrollView hits the top of the screen

and

2. Do I need to take the keyboard's height into consideration when it is raised while doing that?

I can use the keyboard notifications to detect when the keyboard is or isn't raised and simply toggle a property to the keyboard's height.

var keyboardHeight: CGFloat = 0.0

@objc fileprivate func keyboardWillShow(notification: Notification) {

    guard let keyboardDuration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else { return }
    guard let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }

    let keyboardRectangle = keyboardFrame.cgRectValue
    keyboardHeight = keyboardRectangle.height
}

@objc fileprivate func keyboardWillHide(notification: Notification) {

    keyboardHeight = 0.0
}

enter image description here

enter image description here


Solution

  • Seems I only had to check if the contentOffset was less then or equal to 50

    if contentOffset <= -40 {
        handlePagination()
    }
    

    It worked when the keyboard was and wasn't raised.

    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    
        let contentOffset = scrollView.contentOffset.y
    
        if contentOffset <= -40 {
            handlePagination()
        }
    }