How do I implement UIScrollView tiling with paging enabled?

时间:2019-04-17 02:26:00

标签: ios swift uiscrollview infinite-scroll scroll-paging

I am trying to create an infinite scrolling paging UIScrollView I have been following the Advanced UIScrollView Techniques video from WWDC 2010 however I am unsure as to how to create tiling for a paging UIScrollView. I have been using this tutorial for guidance Infinite Paging along with this Stack Exchange answer. Is it possible to create such an effect in a paging UIScrollView or is tiling primarily used only in a continuous scrolling environment. Thank you for your help.

1 个答案:

答案 0 :(得分:1)

如果需要无限滚动,可以在滚动后更改元素位置。 非常简单的示例和肮脏的代码,但我帮了我忙:

import UIKit

class MainVC: UIViewController, UIScrollViewDelegate {

@IBOutlet var scrollView: UIScrollView!

var currentView: UIView?
var nextView: UIView?
var previousView: UIView?

override func viewDidLoad() {
    super.viewDidLoad()
    scrollView.isPagingEnabled = true
    scrollView.delegate = self
    generateViews()
}

func generateViews() {
    let screenSize = UIScreen.main.bounds
    currentView = UIView()
    nextView = UIView()
    previousView = UIView()

    addPosition(cView: currentView!, nView: nextView!, pView: previousView!)

    currentView?.backgroundColor = .red
    nextView?.backgroundColor = .green
    previousView?.backgroundColor = .blue

    scrollView.addSubview(currentView!)
    scrollView.addSubview(previousView!)
    scrollView.addSubview(nextView!)
    scrollView.contentSize = CGSize(width: screenSize.width * 3, height: screenSize.height)

}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    if scrollView.contentOffset.x >= (UIScreen.main.bounds.width * 2) {
        addPosition(cView: nextView!, nView: previousView!, pView: currentView!)
    } else if scrollView.contentOffset.x == 0 {
        addPosition(cView: previousView!, nView: currentView!, pView: nextView!)
    }
    scrollView.contentOffset = CGPoint(x: UIScreen.main.bounds.width, y: 0)
}

func addPosition(cView: UIView, nView: UIView, pView: UIView) {
    let screenSize = UIScreen.main.bounds
    cView.frame = CGRect(origin: CGPoint(x: screenSize.width, y: 0), size: screenSize.size)
    nView.frame = CGRect(origin: CGPoint(x: screenSize.width * 2, y: 0), size: screenSize.size)
    pView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: screenSize.size)

    currentView = cView
    nextView = nView
    previousView = pView
}

}