UIScrollView: paging horizontally, scrolling vertically?

后端 未结 20 1477
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 09:09

How can I force a UIScrollView in which paging and scrolling are on to only move vertically or horizontally at a given moment?

My understanding is that

20条回答
  •  不知归路
    2020-11-27 09:49

    For those looking in Swift at @AndreyTarantsov second solution its like this in code:

        var positionScroll:CGFloat = 0
    
        func scrollViewWillBeginDragging(scrollView: UIScrollView) {
            positionScroll = self.theScroll.contentOffset.x
        }
    
        func scrollViewDidScroll(scrollView: UIScrollView) {
            if self.theScroll.contentOffset.x > self.positionScroll || self.theScroll.contentOffset.x < self.positionScroll{
                 self.theScroll.pagingEnabled = true
            }else{
                self.theScroll.pagingEnabled = false
            }
        }
    

    what we are doing here is to keep the current position just before scrollview gets dragged and then check if either x has increased or decreased compared to the current position of x. If yes, then set the pagingEnabled to true, if no (y has increased/decreased) then set to pagingEnabled to false

    Hope that is useful to new comers!

提交回复
热议问题