I have a UIView
like iPhone\'s Springboard. I have created it using a UIScrollView
and UIButtons
. I want to disable horizontal scrolli
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
Use this single line.
self.automaticallyAdjustsScrollViewInsets = NO;
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)
You can select the view, then under Attributes Inspector
uncheck User Interaction Enabled
.
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).
Once I did it replacing the UIScrollView with a UITableView with only 1 cell, it worked fine.