在 Swift 中为 PageViewController 创建 UICollectionView 数组

Creating an Array of UICollectionViews for PageViewController in Swift

我已经设置了一个 CollectionViewController,它将从数据源创建一个 CollectionView。现在我想使用 PageViewController 在 CollectionView 中滑动,但我不知道如何创建包含 CollectionView 的数组。

到目前为止,我仅通过以下方式展示了其中一个 CollectionView:

let CollectionVC = storyboard?.instantiateViewController(withIdentifier: "CollectionView") as! CollectionViewController
    CollectionVC.itemStrings = matrixArray[0].makeString()
    CollectionVC.columns = problem.columns
    CollectionVC.rows = problem.rows
    self.present(CollectionVC, animated: true, completion: nil)

呈现一个视图效果很好。

但是现在我需要创建一个可以被 PageViewController 读取的数组来生成 PageView,我该怎么做?我什至不确定 PageViewController 数据源所需的格式,据我从其他教程中可以看出,它应该是 UIViewController 的数组而不是 UICollection[ 类型的数组=62=] 正如我计划的那样,如果是这样的话,我怎样才能使它与 CollectionViews 一起工作?

关于如何创建可用作页面数据源的数组的任何建议ViewController?

更多说明

这是一张它应该如何看的图片:

每个屏幕基本上都是由集合ViewController创建的,页面ViewController组织它们,并可以按照分页指示在这些屏幕中滑动。

//编辑:

感谢 Puneet Sharma 的回答。我确信这已经非常接近我正在寻找的解决方案。但是由于我在编程方面完全是一个自学成才的菜鸟,所以我不太确定将所有这些信息放在哪里。

到目前为止我有 2 个控制器,一个 ViewController:

class ViewController: UIViewController {

//Initialize Variables:
var matrixArray = Array<Matrix>()
var basicArray = Array<Array<Int>>()
var maxArray = Array<Double>()
var currentSolutionArray = Array<Array<Double>>()
var isOptimal = false
var isCyceling = false
var CollectionViewArray: [UICollectionView] = []

//The outlets are for later
@IBOutlet weak var myObjectionFunction: UITextField!

@IBOutlet weak var myConstraint1: UITextField!
@IBOutlet weak var myConstraint1RightSide: UITextField!

@IBOutlet weak var myConstraint2: UITextField!
@IBOutlet weak var myConstraint2RightSide: UITextField!

@IBOutlet weak var myConstraint3: UITextField!
@IBOutlet weak var myConstraint3RightSide: UITextField!


//StartButton
@IBAction func startButton(_ sender: Any) {

    //Initializing Objection Function
    let objFunction = [-40.0,-30.0,0.0,0.0,0.0,0.0]

    // Initializing Nr. of Rows and Columns of the Matrix
    let rows = 4
    let columns = 6

    // Initializing constraints
    let constraint0 = [1.0,1.0,1.0,0.0,0.0,8.0]
    let constraint1 = [2.0,1.0,0.0,1.0,0.0,12.0]
    let constraint2 = [2.0,3.0,0.0,0.0,1.0,18.0]

    //Initalize an Array containing all constraints
    let constraints = [constraint0, constraint1, constraint2]

    //Alternative for use of UserData -> Delete objFuntion, rows, columns, constraint0..2, constraintsArray
    //let problem = getData().0
    //let constraints = getData.1
    let problem = LinearProblem.createLP(rows: rows, columns: columns, objFunction: objFunction, constraints: constraints)


    // Initializing Current solution (No need to change anything)
    let currentSolution = Array(repeating: 0.0, count: constraints.count)



    print("Initial Problem: ")
    print(problem)
    print("\n")


   let solution = PrimalSimplex(problem: problem, currentSolution: currentSolution)

    matrixArray = solution.0
    basicArray = solution.1
    maxArray = solution.2
    currentSolutionArray = solution.3
    isOptimal = solution.4
    isCyceling = solution.5

    let CollectionVC = storyboard?.instantiateViewController(withIdentifier: "CollectionView") as! CollectionViewController
    CollectionVC.itemStrings = matrixArray[0].makeString()
    CollectionVC.columns = problem.columns
    CollectionVC.rows = problem.rows
    self.present(CollectionVC, animated: true, completion: nil) 
 }
}

它基本上是一个带有开始按钮的屏幕,当它被按下时会启动算法并显示下一个视图。

然后是这个合集ViewController:

class CollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

@IBOutlet weak var myCollectionView: UICollectionView!

    //Is also set in Storyboard
    let reuseIdentifier = "cell" 

    var itemStrings: Array<String?> = []
    var rows: Int = 0
    var columns: Int = 0   


//
//Setup CollectionView: Table to display LPs including Datasource
//

// MARK: - UICollectionViewDelegate protocol

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    // handle tap events
    let newPath = indexPath.item + 1
    print("You selected cell #\(newPath)")
}

// calculate height and width of cell
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let width = collectionView.bounds.width
    let gaps = columns-1

    let tmpWidth = width - CGFloat(gaps)
    let itemWidth = tmpWidth / CGFloat(columns)

    let height = collectionView.bounds.height

    let tmpHeight = height - CGFloat(gaps)
    let itemHeight = tmpHeight / CGFloat(rows)

    return CGSize(width: itemWidth, height: itemHeight)
}

// CellSpacing vertical
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {

    return CGFloat(3)
}

// CellSpacing horizontal
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {

    return CGFloat(1)
}

// change background color when user touches cell
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)

    //Change color
    if cell?.backgroundColor == UIColor(red:0.96, green:0.40, blue:0.40, alpha:1.0) {
        cell?.backgroundColor = UIColor(red:0.94, green:0.94, blue:0.94, alpha:1.0)
    }
    else{
        cell?.backgroundColor = UIColor(red:0.96, green:0.40, blue:0.40, alpha:1.0)
    }
}

// MARK: - UICollectionViewDataSource protocol

// tell the collection view how many cells to make
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    let numberOfItems = rows*columns
    return numberOfItems
}

// make a cell for each cell index path
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    // get a reference to our storyboard cell
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell

    // Use the outlet in our custom class to get a reference to the UILabel in the cel

    cell.myLabel.text = itemStrings[indexPath.item]
    cell.backgroundColor = UIColor(red:0.94, green:0.94, blue:0.94, alpha:1.0)

    // Change shape of cells
    cell.layer.cornerRadius = 8

    return cell
 }
}

这些也是目前我故事板中仅有的元素。

我想我需要在 Storyboard 中添加 PageViewController 并用你的 HomeViewController 代码填充它。然后将 Storyboard 中的 segue 从开始按钮更改为 HomeViewController.

我不明白的部分是将要创建的ChildVC。我需要将该部分添加到我的 ViewController 吗?那么 IndexedCollectionViewController class 呢?我是否需要为此创建一个额外的文件,或者我是否可以将其放入我的 collectionView 某处?

那么这个函数呢

private func viewController(atIndex index:Int) -> IndexedCollectionViewController

那去哪儿了?我认为在我的情况下会在 ViewController class 中,我只是调用开始按钮中的方法 ?

很抱歉提出所有这些非常简单的问题,但作为一个自学成才的编码员,有时很难掌握事物背后的概念 ^^

在我看来,UIPageViewController 文档有点含糊。 争论的焦点是一种方法的存在:

func setViewControllers(_ viewControllers: [UIViewController]?, 
              direction: UIPageViewControllerNavigationDirection, 
               animated: Bool, 
             completion: ((Bool) -> Void)? = nil)

所有教程都在这个数组中传递一个视图控制器,它们是正确的of-course。但是因为这个方法的存在,我假设我可以把所有需要显示的视图控制器放在一个数组中到 pageviewcontroller.

但是,实际上需要这个方法来传递需要在动画之后显示的视图控制器。如果我们需要在屏幕上显示多个视图(视图控制器),我们可以将这些视图传递到数组中。但这种情况很少见,因此所有教程都显示在数组中传递单个 VC。

UIPageViewControllerDatasource用于提供额外的视图控制器。

您可以用这种方式实现您的 viewcontroller 页面viewcontroller。

// Extension on UIViewController to insert child view controller
extension UIViewController {

    func insertChildController(_ childController: UIViewController, intoParentView parentView: UIView) {
        childController.willMove(toParentViewController: self)

        self.addChildViewController(childController)
        childController.view.frame = parentView.bounds
        parentView.addSubview(childController.view)

        childController.didMove(toParentViewController: self)
    }

}

// Subclass of UICollectionViewController to create IndexedCollectionViewController. This is done to introduce an integer property to index collectionview controllers
class IndexedCollectionViewController:UICollectionViewController {
    var index:Int = 0
}


class HomeViewController: UIViewController {

    var pageViewController:UIPageViewController!

    override func viewDidLoad() {
        super.viewDidLoad()
        addPageViewController()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

// MARK:- PageView
extension HomeViewController:UIPageViewControllerDataSource, UIPageViewControllerDelegate {

    fileprivate func addPageViewController() {
        if !self.isViewLoaded {
            return
        }

        self.pageViewController = UIPageViewController(transitionStyle: UIPageViewControllerTransitionStyle.scroll, navigationOrientation: UIPageViewControllerNavigationOrientation.horizontal, options: nil)

        let firstVC = self.viewController(atIndex: 0)
        pageViewController.setViewControllers([firstVC], direction: UIPageViewControllerNavigationDirection.forward, animated: true, completion: nil)
        pageViewController.dataSource = self
        pageViewController.delegate = self
        self.insertChildController(pageViewController, intoParentView: self.view)
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        var index = (viewController as! IndexedCollectionViewController).index
        index = index+1
        return self.viewController(atIndex: index)
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        var index = (viewController as! IndexedCollectionViewController).index
        if(index == 0){return nil}
        index = index-1
        return self.viewController(atIndex: index)
    }

    // Method that creates viewcontroller
    private func viewController(atIndex index:Int) -> IndexedCollectionViewController {

        // This method will work only if you change the Class of CollectionViewController to IndexedCollectionViewController in your storyboard
        let vc = storyboard?.instantiateViewController(withIdentifier: "CollectionView") as! IndexedCollectionViewController
        vc.itemStrings = matrixArray[index].makeString()
        vc.index = index
        vc.columns = problem.columns
        vc.rows = problem.rows
        return vc
    }
}

在我看来,您的视图布局应如下所示。
VC1 :-> 具有开始按钮的视图控制器,并将显示 vc2。
VC2 :-> 显示页面浏览量的视图控制器。
它可以是一个 PageViewController 本身(因为 UIPageViewController 是 UIViewController 的子类)或者一个简单的 ViewController 添加了 PageViewController 作为 child VC.

页面ViewController,本质上是以页面的形式显示其他ViewController的内容。在您的案例中,这些其他 viecontroller 是 CollectionViewController。