以下情况:传输数据从一个视图到另一个Swift 3
我有2个控制器,一个ViewController和一个CollectionViewController。普通的ViewController应该从用户那里收集数据,并且当单击开始按钮时,算法解决了这个问题并返回结果。结果应该被传送到CollectionViewController,并且基于解决方案构建CollectionView。
下面是我用于启动按钮的代码。正如你所看到的,该算法被调用,结果存储在几个变量中,现在我试图将matrixArray传递给我的CollectionViewController(它是第一次测试)。该CollectionViewController应该使用这个存储阵列中的数据呈现某种形式的画面
@IBAction func startButton(_ sender: Any) {
...
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.testMatrix = matrixArray
}
到目前为止好,数据到达是在CollectionViewController可用按下起动按钮后。但是当我尝试使用数据来构建CollectionView时,我收到一条错误消息。
这是我在collectionViewController用于构建的CollectionView的代码(它的工作前,用静态值,当我尝试使用值,该算法返回......出现的问题):
class CollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var myCollectionView: UICollectionView!
// Creates an empty array for the values
var testMatrix = Array<Matrix>()
//Setup CollectionView: Table to display LPs
let reuseIdentifier = "cell"
var items = testMatrix[0] <----ERROR
// MARK: - UICollectionViewDataSource protocol
// tell the collection view how many cells to make
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
// 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 cell
cell.myLabel.text = items[indexPath.item]
cell.backgroundColor = UIColor(red:0.94, green:0.94, blue:0.94, alpha:1.0) // make cell more visible in our example project
// Change shape of cells
cell.layer.cornerRadius = 8
return cell
}
....
显示在VAR项目
错误= testMatrix [0]:
Cannot use instance member 'testMatrix' within property initializer; property initializers run before 'self' is available
我可以理解,这里的Xcode有问题,因为它不能确保testMatrix已存储的值....我想这个问题。我试图使用,如果让/警卫声明,但没有解决问题。
任何关于如何解决这个问题的建议或什么是错误的? 也许有更好的方法将数据从第一个VC传输到另一个?
使用,在'viewDidLoad中()'或'viewWillAppear中()' –
https://stackoverflow.com/a/45423454/8432814阅读这个答案更多的澄清 –