Home > Net >  How to place multiple UIView horizontally in ScrollView?
How to place multiple UIView horizontally in ScrollView?

Time:03-29

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?

CodePudding user response:

Don't add the views to the scrollView Directly

  1. add Horizontal stackView to the scrollView
  2. make (leading trailing top bottom) of stackView equal to scrollView (leading trailing top bottom)
  3. make stackView's height equal to scrollView's height
  4. 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)
    }
}
  • Related