How to disable horizontal scrolling of UIScrollView?

前端 未结 14 1690
伪装坚强ぢ
伪装坚强ぢ 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:51

    Introduced in iOS 11 is a new property on UIScrollView

    var contentLayoutGuide: UILayoutGuide
    

    The documentation states that you:

    Use this layout guide when you want to create Auto Layout constraints related to the content area of a scroll view.

    Along with any other Autolayout constraints that you might be adding you will want to constrain the widthAnchor of the UIScrollView's contentLayoutGuide to be the same size as the "frame". You can use the frameLayoutGuide (also introduced in iOS 11) or any external width (such as your superView's.)

    example:

    NSLayoutConstraint.activate([
      scrollView.contentLayoutGuide.widthAnchor.constraint(equalTo: self.widthAnchor)
    ])
    

    Documentation: https://developer.apple.com/documentation/uikit/uiscrollview/2865870-contentlayoutguide

    0 讨论(0)
  • 2020-12-02 08:53

    Use this single line.

    self.automaticallyAdjustsScrollViewInsets = NO;

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-02 08:59

    You can select the view, then under Attributes Inspector uncheck User Interaction Enabled .

    0 讨论(0)
  • 2020-12-02 08:59

    I struggled with this for some time trying unsuccessfully the various suggestions in this and other threads.

    However, in another thread (not sure where) someone suggested that using a negative constraint on the UIScrollView worked for him.

    So I tried various combinations of constraints with inconsistent results. What eventually worked for me was to add leading and trailing constraints of -32 to the scrollview and add an (invisible) textview with a width of 320 (and centered).

    0 讨论(0)
  • 2020-12-02 08:59

    Once I did it replacing the UIScrollView with a UITableView with only 1 cell, it worked fine.

    0 讨论(0)
提交回复
热议问题