Reputation: 2001
I have a UIScrollView added in a storyboard, referenced as:
@IBOutlet weak private var myScrollView: UIScrollView!
I want to add a UIViewController so need a containerview.
In the first instance I go to add a simple UIView with a black background (to see it) so added into ViewDidLoad:
let containerView = UIView()
containerView.frame = CGRect(x: 50, y: 150, width: 200, height: 200)
containerView.backgroundColor = UIColor.black
myScrollView.addSubview(containerView)
and... nothing.
Looking around for solutions I found I can use
self.view.addSubview(myScrollView)
But 1. Surely myScrollView is already added to the view? and 2. I cannot scroll the new view in myScrollView
Can anyone help me get over this initial hurdle?
Upvotes: 1
Views: 682
Reputation: 25261
Your code looks good to me. Here is what it looks like when I run it by myself.
To answer your question
Set the background of your scroll view to another color like what I am doing. Then you can figure out what goes wrong. You have to add your container view to your Scroll View, not self.view
, which is the view controller. If you add to self.View
, your container view will be pinned to your view controller and will not scroll with scroll view. It will instead cover the scroll view
Scroll view cannot scroll if its content size is smaller than the size of the view. Namely, it's by default too short to be scrollable. So simply make it higher by this code
scrollView.contentSize = CGSize(width: scrollView.contentSize.width, height: 2000)
Upvotes: 1
Reputation: 3499
In order to scroll the content size must be greater than the frame size.
// If the scroll view is not showing, check its frame
scrollView.frame = CGRect(x: 0, y: 318, width: 375, height: 248)
// Content size must be greater than frame size
scrollView.contentSize = CGSize(width: 400, height: 500)
let containerView = UIView()
containerView.frame = CGRect(x: 50, y: 150, width: 200, height: 200)
containerView.backgroundColor = UIColor.black
scrollView.addSubview(containerView)
Upvotes: 1