Reputation:
I have a MainViewController
with some elements inside. I want the whole view to be vertically scrollable.
I made this BaseScrollableViewController
class:
class BaseScrollableViewController: UIViewController, UIScrollViewDelegate {
lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.delegate = self
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
return scrollView
}()
lazy var contentView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(scrollView)
scrollView.addSubview(contentView)
NSLayoutConstraint.activate([
scrollView.topAnchor.constraint(equalTo: view.topAnchor),
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
contentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor),
contentView.heightAnchor.constraint(equalTo: scrollView.heightAnchor)
])
}
}
Then I made the MainViewController
a subclass of this BaseScrollableViewController
. Inside, I use contentView
to add all the subviews.
Now it scrolls vertically. However, when I scroll down to the bottom, here is what is shows:
Note that there is an empty space at the bottom.
I have tried the scrollView.contentInsetAdjustmentBehavior = .never
, but then the scrollView becomes not scrollable.
So how can I fix this? Thanks!
Upvotes: 0
Views: 372
Reputation: 5183
For a scrollView to be scrollable, its subviews need to be bigger than the scrollView. By specifying the following constraint contentView.heightAnchor.constraint(equalTo: scrollView.heightAnchor)
on the BaseScrollableViewController
you are specifying that the contentView
will have the same height of the scrollView
, thus making the view not scrollable when setting scrollView.contentInsetAdjustmentBehavior = .never
.
You can test this by adding a multiplier value on the contentView height constraint:
contentView.heightAnchor.constraint(equalTo: scrollView.heightAnchor, multiplier: 1.5)
And enabling
`scrollView.contentInsetAdjustmentBehavior = .never`
Upvotes: 1