0

我正在尝试创建一个无限滚动分页UIScrollView,我一直在关注Advanced UIScrollView Techniques视频,WWDC 2010但是我不确定如何为分页创建平铺UIScrollView。我一直在使用本教程来指导Infinite Paging 以及这个 Stack Exchange 答案。是否可以在分页中创建这样的效果,UIScrollView或者平铺主要仅用于连续滚动环境。谢谢您的帮助。

4

1 回答 1

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
}

}
于 2019-04-17T07:11:18.147 回答