Search code examples
iosswiftuiscrollview

Can distinguish the between user scrolling and programmatically scrolling?


I've put a scroll event on scrollViewDidScroll. But when the user scrolls, It also works when using setContentOffSet. I want to make it work only when the user scrolls.

func scrollViewDidScroll(_ scrollView: UIScrollView) {
            if (self.lastContentOffset > scrollView.contentOffset.y) {
                let contentSize = scrollView.contentSize.height
                let tableSize = scrollView.frame.size.height - scrollView.contentInset.top - scrollView.contentInset.bottom
                let canLoadFromBottom = contentSize > tableSize
                // Offset
                let currentOffset = scrollView.contentOffset.y
                let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height
                let difference = maximumOffset - currentOffset
                if canLoadFromBottom, difference <= -85.0{
                    loadMore()
                }
            self.lastContentOffset = scrollView.contentOffset.y
    }

Solution

  • If you scroll in code, you receive the delegate method just once immediately after, so it is easy to raise a Bool flag before scrolling in code and detect this in the delegate method.