UIScrollView max and min contentOffsets?

Given a UIScrollView with any of its default settings (like contentInset), how can I get the minimum and maximum contentOffset?

those. when the user scrolls all the way to the left, what will the contentOffset say as?

those. if the user had to scroll all the way down to the bottom right, what would contentOffset tell how?

+3


source to share


2 answers


Imagine we have the following UIScrollView:

  • contentSize: 500 x 500

  • frame / border size: 200 x 200

  • contentInsets: (10, 10, 10, 10)

Calculated contentOffices:

  • Min contentOffset:
    • .x: -contentInset.left

      (-10)
    • .y: -contentInset.top

      (-10)
  • Maximum contentOffice
    • .x: contentSize.width - bounds.width + contentInset.right

      (310)
    • .y: contentSize.height - bounds.height + contentInset.bottom

      (310)

Usually UIScrollView starts with contentOffset = (0, 0)

. However, when you add contentInsets, it starts to shift with a negative amount. When you view the first position in the view to not see the content, you will be in contentOffset = (0,0)

.



A similar thing happens at the end, where instead of 300 is the maximum offset, 310 becomes the maximum.

func minContentOffset(scrollView: UIScrollView) -> CGPoint {
    return CGPoint(
        x: -scrollView.contentInset.left,
        y: -scrollView.contentInset.top)
}

func maxContentOffset(scrollView: UIScrollView) -> CGPoint {
    return CGPoint(
        x: scrollView.contentSize.width - scrollView.bounds.width + scrollView.contentInset.right,
        y: scrollView.contentSize.height - scrollView.bounds.height + scrollView.contentInset.bottom)
}

      

Then you can create a function that uses both of these functions to define the scroll scroll:

func canVerticallyScroll(scrollView: UIScrollView) -> Bool {
    let scrollableHeight = maxContentOffset(scrollView: scrollView).y
        - minContentOffset(scrollView: scrollView).y
    let viewableHeight = scrollView.bounds.height
    return viewableHeight < scrollableHeight
}

      

+7


source


select the origin

CGPoint(x: -contentInset.left, y: -contentInset.top)

      

scroll down



CGPoint(x: 0, y: -contentInset.top + contentSize.height - frame.height))

      

scroll right

CGPoint(x: 0, y: -contentInset.left + contentSize.width - frame.width))

      

0


source







All Articles