Search code examples
swiftuikitscrollviewpadding

How can you add padding between views in a UIScrollView in Swift?


I have a simple UIScrollView with images. For simplicity it's a scroll view with two image views as subviews. The image views are anchored to each other. Unfortunately, the images are stuck together. I tried adding top padding to each image but it did affect the spacing at all.

https://i.sstatic.net/91cmw.jpg

Is there some way to add padding bewteen elements in a scroll view?

Thanks.


Solution

  • Your constraints are likely not behaving like you expect. My strong suggestion is to use a UIStackView instead, and bind it to the scroll view via constraints, but not your images.

    let stackView = UIStackView()
    stackView.axis = .vertical
    stackView.spacing = 8 // or whatever you want
    
    stackView.addArrangedSubview(image1)
    stackView.addArrangedSubview(image2)
    
    scrollView.addSubview(stackView)
    stackView.translatesAutoresizingMask = false
    
    // finish the constraints like the first, but for .trailing, .top, and .bottom
    NSLayoutConstraint.activate([
      stackView.leadingAnchor(constraintEqualTo: scrollView.leadingAnchor),
      ...
    ])