UIScrollView scroll by offset

I have this situation:

  • one scrollView matching all screens
  • N "Cells" inside scrollView, each of them contains a label
  • each cell is 80px high
  • fixed green mask (UIView)

I programmatically create cells (UIView) with a label inside and set the contentSize of the scroll correctly.

I know that

scrollView.setContentOffset(CGPoint(x: 0, y: 80.0), animated: true)

move the scroll by 80.

How can I “override” the scroll behavior to always scroll to 80? What I want is a kind of collector behavior. Is it possible?

enter image description here

+5
source share
4 answers

You can use the following method when your layout changes

func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    myScrollView.contentOffset.y += 80
}
+3
source

, :

let viewHeight: CGFloat = 80.0

func scrollViewWillBeginDragging(scrollView: UIScrollView) {
    startContentOffsetY = scrollView.contentOffset.y
}

func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    targetContentOffsetY = targetContentOffset.memory.y
    if startContentOffsetY - targetContentOffsetY < 0 {
        scrollDirection = ScrollDirection.Bottom.rawValue
    } else {
        scrollDirection = ScrollDirection.Top.rawValue
    }
    let gap = targetContentOffsetY % viewHeight
    var offset: CGFloat = 0.0
    if (targetContentOffsetY - gap) % viewHeight == 0 {
        offset = -gap * scrollDirection
    } else {
        offset = gap * scrollDirection
    }
    let newTarget = targetContentOffsetY + (offset * scrollDirection)
    targetContentOffset.memory.y = newTarget
}
+1

there might be something like this: (you need to add some checks) make the delegate class to view the scroll (UIScrollViewDelegate)

now add this function to your UIScrollViewDelegate

myScrollView.delegate = instanceOfUIScrollViewDelegate;
func scrollViewDidScroll(scrollView: UIScrollView) {
    scrollView.contentOffset.y+=80;
}
0
source

You can use this method

scrollView.setContentOffset( CGPoint(x:0,y:30), animated:true )

0
source

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


All Articles