UIScrollView 中图像之间的边距

Tim*_*Tim 4 uiscrollview scroll-paging nslayoutconstraint swift

我追求的效果:只有在滚动时才可见的图像之间的间距(如照片应用程序)。

许多旧的 obj-c 答案建议将滚动视图的边界扩展到屏幕外以使其页面更远,并使这个屏幕外空间成为图像之间的间隙。

pagingEnabled 的文档指出:

如果此属性的值为 YES,则当用户滚动时,滚动视图将在滚动视图边界的倍数处停止。

因此,在尝试更改倍数值时,我扩展了 scrollView 的宽度,并启用了左分页。然而,我没有实现页面超越差距的答案 - 他们总是把它留在视野中:

在此处输入图片说明

那么如果滚动宽度更长,为什么它不分页合适的距离呢?

    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)
Run Code Online (Sandbox Code Playgroud)

mat*_*att 6

正如文档告诉您的那样,一个“页面”宽度是滚动视图的边界宽度。

因此,假设图像的宽度为 100 磅。假设图像之间的空间为 10 点。然后:

  • 滚动视图的宽度必须为 110 磅。

  • 空间必须在每个图像的每一侧分布 5 个点,如下所示(假设我们有 3 个图像):

    5pts - 100pts (im) - 10pts - 100pts (im) - 10pts - 100pts(im) - 5pts
    
    Run Code Online (Sandbox Code Playgroud)

这将导致每个页面包含一个 100pt 的图像,每边有 5 pts 的空间,总共 110 pts,滚动视图的宽度:

    5pts - 100pts (im) - 10pts - 100pts (im) - 10pts - 100pts(im) - 5pts
    |                      |                      |                    |
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明