'How to place multiple UIView horizontally in ScrollView?
I have a scrollView stretched to the full screen by constraints. I'm trying to make it 4 UIViews arranged horizontally one after the other.
func createSubViews() {
let colors: [UIColor] = [.systemRed, .systemGreen, .systemYellow, .systemBlue]
for index in 0...3 {
let page = UIView()
page.backgroundColor = colors[index]
pages.append(page)
scrollView.addSubview(page)
setupConstraints(index: index)
}
}
func setupConstraints(index: Int) {
pages[index].translatesAutoresizingMaskIntoConstraints = false
var constraints = [
pages[index].topAnchor.constraint(equalTo: scrollView.topAnchor),
pages[index].bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
pages[index].widthAnchor.constraint(equalToConstant: width/4)
]
if index == 0 {
constraints.append(
pages[index].leadingAnchor.constraint(equalTo: scrollView.leadingAnchor)
)
} else {
constraints.append(
pages[index].leadingAnchor.constraint(equalTo: pages[index - 1].trailingAnchor)
)
}
NSLayoutConstraint.activate(constraints)
}
Why doesn't it work?
Solution 1:[1]
Don't add the views to the scrollView Directly
- add Horizontal stackView to the scrollView
- make (leading trailing top bottom) of stackView equal to scrollView (leading trailing top bottom)
- make stackView's height equal to scrollView's height
- add your subViews to the stackView as ArrangedSubviews
@IBOutlet weak var stackView: UIStackView!
var pages: [UIView] = []
func createSubViews() {
let colors: [UIColor] = [.systemRed, .systemGreen, .systemYellow, .systemBlue, .systemGreen, .systemBlue, .systemYellow]
let width = UIScreen.main.bounds.width
for index in 0 ..< colors.count {
let page = UIView()
page.translatesAutoresizingMaskIntoConstraints = false
pages[index].widthAnchor.constraint(equalToConstant: width/4).isActive = true
page.backgroundColor = colors[index]
pages.append(page)
stackView.addArrangedSubview(page)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mohammed aboarab |