swiftuiscrollviewnslayoutconstraintscroll-paging

Margin between images in UIScrollView


The effect I'm after: Having spacing between images that is only visible while scrolling (like the photos app).

A lot of old obj-c answers suggest extending the scroll view's bounds offscreen to make it page farther, and making this offscreen space the gap between images.

The documentation for pagingEnabled states:

If the value of this property is YES, the scroll view stops on multiples of the scroll view’s bounds when the user scrolls.

So in trying to change the multiples value, I extended the scrollView's width, and left paging enabled. Yet no answers I implement page past the gap - they always leave it in view:

enter image description here

So if the scroll width is longer, why isn't it paging the proper distance?

    let gapMargin = CGFloat(20)
    scrollView.frame = CGRect(x: 0, y: 0, width: view.frame.width + gapMargin, height: view.frame.height)
    let exdScrollWidth = scrollView.frame.width

    //1
    let imageView1 = UIImageView()
    imageView1.backgroundColor = UIColor.green
    imageView1.frame = CGRect(x: 0, y: 0, width: exdScrollWidth - gapMargin, height: scrollView.bounds.size.height)

    //2
    let imageView2 = UIImageView()
    imageView2.backgroundColor = UIColor.yellow
    imageView2.frame = CGRect(x: exdScrollWidth, y: 0, width: exdScrollWidth - gapMargin, height: scrollView.bounds.size.height)

    //3
    let imageView3 = UIImageView()
    imageView3.backgroundColor = UIColor.red
    imageView3.frame = CGRect(x: exdScrollWidth * 2, y: 0, width: exdScrollWidth - gapMargin, height: scrollView.bounds.size.height)

    scrollView.contentSize.width = exdScrollWidth * 3

    scrollView.addSubview(imageView1)
    scrollView.addSubview(imageView2)
    scrollView.addSubview(imageView3)

Solution

  • It turns out I had an equal widths constraint set up that I'd forgotten about. This meant the multiple by which the scrollview paged was fixed at the width of the superview.