gpt4 book ai didi

ios - 在 Swift 中为 PageViewController 创建 UICollectionView 数组

转载 作者:行者123 更新时间:2023-11-30 12:07:02 25 4
gpt4 key购买 nike

我已经设置了一个 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)

这对于呈现一个 View 来说效果很好。

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

关于如何创建这样一个可用作 PageViewController 数据源的数组,有什么建议吗?

更多说明

这是最后的图片:

CollectionView

每个屏幕基本上都是由 CollectionViewController 创建的,PageViewController 负责组织它们,并使得可以按照分页指示在这些屏幕上滑动。

//编辑:

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

到目前为止我有 2 个 Controller ,一个 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)
}
}

它基本上是一个带有开始按钮的屏幕,按下按钮时会启动算法并呈现下一个 View 。

然后是这个 CollectionViewController:

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中唯一的元素。

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

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

这个函数怎么样

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

那去哪儿了?我认为在我的情况下,这将在 ViewController 类中,并且我只需调用开始按钮中的方法?

对所有这些非常简单的问题感到抱歉,但作为一名自学成才的程序员,有时很难掌握事物背后的概念 ^^

最佳答案

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

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

所有教程都在这个数组中传递一一 View Controller ,它们当然是正确的。但由于这个方法的存在,我假设我可以将所有需要显示的 View Controller 以数组形式提供给 pageviewcontroller。

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

UIPageViewControllerDatasource用于提供额外的 View Controller 。

您可以实现以这种方式保存 pageviewcontroller 的 View Controller 。

// 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
}
}

在我看来,您的 View 布局应该如下所示。
VC1 :-> View Controller 有开始按钮,并且将呈现 vc2。
VC2 :-> 显示页面 View 的 View Controller 。
它可以是一个 PageViewController 本身(因为 UIPageViewController 是 UIViewController 的子类),也可以是一个简单的 ViewController,其中 PageViewController 作为子 VC 添加。

PageViewController,本质上以页面的形式显示其他ViewControllers内容。您的情况中的其他 viecontroller 是 CollectionViewController。

关于ios - 在 Swift 中为 PageViewController 创建 UICollectionView 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46562774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com