Reputation: 531
I wanna add scroll view in my project but in swift 5 I can't add it I tried many ways
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var imageViewBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var imageViewLeadingConstraint: NSLayoutConstraint!
@IBOutlet weak var imageViewTopConstraint: NSLayoutConstraint!
@IBOutlet weak var imageViewTrailingConstraint: NSLayoutConstraint!
Upvotes: 15
Views: 46244
Reputation: 630
You can skip constraints altogether.
scrollView.contentSize = (CGSize(width: desiredWidth, height: desiredHeight)
The desired width can be either a number or the width of another view. You can take the main view's width for exemple, by creating an IBOutlet to it: scrollView.contentSize = (CGSize(width: mainView.frame.size.width, height: desiredHeight)
The desired height is whatever value you require for the content to be shown in full while scrolling.
I find this way much easier to understand and control.
Upvotes: 4
Reputation: 4066
You don't need to uncheck Content Layout Guides(it's there to help us). It's actually not that hard to set it up. Here's how to do it using Xcode 11+ and supporting iOS 11+
1 - Add ScrollView and set top, bottom, leading and trailing constraints to 0 in relation to its superview
2 - Add a Content View(any UIView), drag a connection to the Content Layout Guide and set leading,top,trailing and bottom constraints to 0(make sure to set it to 0)
3 - Drag from your Content View to the Frame Layout Guide and set it to Equal Width
4 - Add a height constraint constant to the Content View
Upvotes: 14
Reputation: 463
1.Add scrollView(1) in storyboard, add needed constraint to top/bottom/trailing/leading.
2.Then uncheck "Content Layout Guides" in Size inspector section for your scrollView.
3.Then you need to put into your scrollView new UIView(2), its constraints are for top/bottom/trailing/leading to superView(1) and equal width to superView(1).
4.Then the height of your view(2) you can add as constraint or you can add the content, which will give the height to your view(2).
Example with the height setted
Example with the content, which give the height to your view(2)
Upvotes: 27
Reputation: 531
It works 100% when I Disabling the content layout guides in properties
Upvotes: 12
Reputation: 747
If you use interface builder first of all add your scroll view and set scroll view constraint (top, bottom, leading and trailing) as (0,0,0,0). View hierarchy must be like this view -> scroll view -> view(content view)
. Again add constraints for your content view. Content view must have equal width and equal height with parent view (Scroll View). Control drag from content view to scroll view in Document Outline
For more information you can look at this https://developer.apple.com/library/archive/documentation/UserExperience/Conceptual/AutolayoutPG/WorkingwithScrollViews.html
Upvotes: 9