Reputation: 180
I'm trying to add a background image that will scroll with my vertical scrollView. Before adding the background image, my scrollView only scroll vertically, but after setting the background image, the scrollView can now scroll horizontally and vertically as if the background image's width is greater than the scrollview's width
let scrollView: UIScrollView = {
let view = UIScrollView()
view.translatesAutoresizingMaskIntoConstraints = false
view.isDirectionalLockEnabled = true
view.isScrollEnabled = true
return view
}()
let backgroundIV: UIImageView = {
let imageView = UIImageView(image: UIImage(named: "background"))
imageView.contentMode = UIView.ContentMode.scaleToFill
return imageView
}()
The function I use to setup my view
private func setupContent() {
scrollViewHeight = viewHeight * 2
[scrollView].forEach { view.addSubview($0) }
scrollView.anchor(top: view.topAnchor, leading: view.leadingAnchor, bottom: view.bottomAnchor, trailing: view.trailingAnchor)
scrollView.contentSize = CGSize(width: 0, height: scrollViewHeight)
[backgroundIV].forEach { scrollView.addSubview($0) }
backgroundIV.anchor(top: scrollView.topAnchor, leading: scrollView.leadingAnchor, bottom: scrollView.bottomAnchor, trailing: scrollView.trailingAnchor, size: .init(width: 0, height: scrollViewHeight))
}
So how should i set my background image so that my scrollview won't scroll horizontally??
Upvotes: 0
Views: 582
Reputation: 180
After applying Vikram Parimi's answer and some further digging, there were two factors that effect my scrollview to become horizontal
The characteristics of constraints between Scroll View and view tells us: the alignment and the size are not contradicted anymore, both of which must be defined to eliminate ambiguity. Which I found out from https://medium.com/@tingyishih/ios-scrollview-constraints-8d8140d329a0
The other factor is that the bug only exist in iphone 11 pro max simulator and not iphone 8 simulator, which can be solve by using safeAreaLayoutGuide
if #available(iOS 11.0, *) {
imageView.widthAnchor.constraintEqualToAnchor(scrollView.safeAreaLayoutGuide.widthAnchor).active = true
} else {
imageView.widthAnchor.constraintEqualToAnchor(scrollView.widthAnchor).active = true
}
Upvotes: 0
Reputation: 777
You have to set the right content sizes for your scrollView or adjust the content.
Set your imageView width equal to your scrollView's width. It will avoid scrollView horizontal scroll. Please find the below code for setting the widthAchor.
imageView.widthAnchor.constraintEqualToAnchor(scrollView.widthAnchor).active = true
Upvotes: 1