How to disable horizontal scrolling of UIScrollView?

前端 未结 14 1907
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 08:17

I have a UIView like iPhone\'s Springboard. I have created it using a UIScrollView and UIButtons. I want to disable horizontal scrolli

14条回答
  •  爱一瞬间的悲伤
    2020-12-02 08:58

    Swift solution

    Create two outlets, one for your view and one for your scroll view:

    @IBOutlet weak var myView: UIView!
    @IBOutlet weak var scrollView: UIScrollView!
    

    Then in your viewDidLayoutSubviews you can add the following code:

    let scrollSize = CGSize(width: myView.frame.size.width, 
                            height: myView.frame.size.height)
    scrollView.contentSize = scrollSize
    

    What we've done is collected the height and width of the view and set the scrollViews content size to match it. This will stop your scrollview from scrolling horizontally.


    More Thoughts:

    CGSizeMake takes a width & height using CGFloats. You may need to use your UIScrollViews existing height for the second parameter. Which would look like this:

    let scrollSize = CGSize(width: myView.frame.size.width, 
                            height: scrollView.contentSize.height)
    

提交回复
热议问题