Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIScrollView scroll by offset

I've this situation:

  • one scrollView that fit all screen
  • N "cells" inside scrollView, each of them contains a label
  • each cell is 80px on height
  • fixed green mask (UIView)

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

I know that

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

move scroll view by 80.

How can I "override" scroll view behaviour in order to always scroll by 80? What i want is sort of picker behaviour.. is this possible?

enter image description here

like image 933
Luca Davanzo Avatar asked Jul 20 '15 11:07

Luca Davanzo


People also ask

What is content offset scroll view?

contentOffset is the point at which the origin of the content view is offset from the origin of the scroll view. In other words, it is where the user has currently scrolled within the scroll view. This obviously changes as the user scrolls.

What is offset in IOS?

Offset this view by the specified horizontal and vertical distances. Assigns a name to the view's coordinate space, so other code can operate on dimensions like points and sizes relative to the named space.

What is content inset?

The custom distance that the content view is inset from the safe area or scroll view edges.


2 Answers

You can use the following method when your layout changes

func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    myScrollView.contentOffset.y += 80
}
like image 97
Sohil R. Memon Avatar answered Sep 28 '22 10:09

Sohil R. Memon


No one answer correctly to the question, so I solved by my self as usually:

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
}
like image 24
Luca Davanzo Avatar answered Sep 28 '22 08:09

Luca Davanzo