UIScrollView scroll by offset

我们两清 提交于 2020-01-03 16:46:54

问题


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?


回答1:


You can use the following method when your layout changes

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



回答2:


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
}



回答3:


maybe something like this: (you need to add some validations) make a delegate class for your scroll view (UIScrollViewDelegate)

now add this function inside your UIScrollViewDelegate

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



回答4:


you can use this method

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



来源:https://stackoverflow.com/questions/31515151/uiscrollview-scroll-by-offset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!