UIScrollView: paging horizontally, scrolling vertically?

后端 未结 20 1470
佛祖请我去吃肉
佛祖请我去吃肉 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:44

    For future reference, I built upon Andrey Tanasov's answer and came up with the following solution that works fine.

    First define a variable to store the contentOffset and set it to 0,0 coordinates

    var positionScroll = CGPointMake(0, 0)
    

    Now implement the following in the scrollView delegate:

    override func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        // Note that we are getting a reference to self.scrollView and not the scrollView referenced passed by the method
        // For some reason, not doing this fails to get the logic to work
        self.positionScroll = (self.scrollView?.contentOffset)!
    }
    
    override func scrollViewDidScroll(scrollView: UIScrollView) {
    
        // Check that contentOffset is not nil
        // We do this because the scrollViewDidScroll method is called on viewDidLoad
        if self.scrollView?.contentOffset != nil {
    
            // The user wants to scroll on the X axis
            if self.scrollView?.contentOffset.x > self.positionScroll.x || self.scrollView?.contentOffset.x < self.positionScroll.x {
    
                // Reset the Y position of the scrollView to what it was BEFORE scrolling started
                self.scrollView?.contentOffset = CGPointMake((self.scrollView?.contentOffset.x)!, self.positionScroll.y);
                self.scrollView?.pagingEnabled = true
            }
    
            // The user wants to scroll on the Y axis
            else {
                // Reset the X position of the scrollView to what it was BEFORE scrolling started
                self.scrollView?.contentOffset = CGPointMake(self.positionScroll.x, (self.scrollView?.contentOffset.y)!);
                self.collectionView?.pagingEnabled = false
            }
    
        }
    
    }
    

    Hope this helps.

提交回复
热议问题