2017-09-25 1 views
-1

다음 상황 :Swift에서 한 뷰에서 다른 뷰로 데이터를 전송하는 중 3

컨트롤러가 2 개인 경우, ViewController와 CollectionViewController가 있습니다. 일반적인 ViewController는 사용자로부터 데이터를 수집하고 시작 버튼을 클릭하면 알고리즘이 문제를 해결하고 그 결과를 반환합니다. Result는 CollectionViewController로 전송되고, 솔루션을 기반으로 CollectionView가 빌드됩니다.

다음은 시작 버튼에 사용한 코드입니다. } 당신이 볼 수 있듯이, 알고리즘이 호출되고, 결과는 여러 변수에 저장되며, 이제는 matrixView를 내 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를 빌드하려고하면 오류 메시지가 나타납니다.

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 
} 
.... 
:

(나는 그 값 알고리즘 수익률을 사용하려고하면 ... 문제가 발생 그것은 정적 값으로, 전에 일) 나는 CollectionView를 구축하기 위해 collectionViewController에 사용 된 코드입니다

오류는 VAR 항목에 표시됩니다 = testMatrix [0] :

Cannot use instance member 'testMatrix' within property initializer; property initializers run before 'self' is available 

는 testMatrix이 값이 저장된 것을 확신 할 수 없기 때문에 내가 생각 ..., 엑스 코드는 여기에 문제가 있음을 이해할 수있다 그게 문제 야. 내가 let/guard 문을 사용하려고했지만 문제가 해결되지 않았다.

수정 방법에 대한 조언이나 실제로 여기에 잘못된 내용이 있습니까? 아마도 첫 번째 VC에서 다른 VC로 데이터를 전송하는 더 좋은 방법이 있을까요?

+0

사용하는 것이 viewDidLoad에'에서()'또는'ViewWillAppear()' –

+0

https://stackoverflow.com/a/45423454/8432814 더 설명에 대한 답변 –

답변

0

클래스 수준에서 다른 종속 속성의 속성을 초기화 할 수 없습니다.

viewDidLoad으로 초기화해야합니다.

var items: Matrix? 
override func viewDidLoad() { 
    super.viewDidLoad() 
    if testMatrix.count>0{ 
     items = testMatrix[0] 
    } 

} 
+0

감사를이 답변을 읽어 보시기 바랍니다. 그것은 효과가 있었다. 하지만 이제는 새로운 문제가 생겼습니다. 내 CollectionViewController 전에 viewDidLoad 메서드가 있습니다 (이 튜토리얼을 따랐습니다 : https://stackoverflow.com/questions/31735228/how-to-make-a-simple-collection-view-with-swift). 추가했지만 시작 버튼을 클릭하면 collectionView가 더 이상 표시되지 않습니다. 아마 아주 간단한 해결책이 있을지 모르지만 프로그래밍에 익숙하지 않으므로 어떻게해야 할 지 전혀 모른다. 아이디어가 있습니까? – Bepa1012

+0

'CollectionVC = storyboard? .instantiateViewController (withIdentifier : "CollectionView")를! CollectionViewController CollectionVC.testMatrix = matrixArray CollectionVC.items = matrixArray [0]' –

+0

답을 다시 한번 고맙습니다. 이것은 불행하게도 효과가 없었습니다. 나는 그걸 가지고 좀 더 놀고 있었지만 ... 지금까지 운이 없다. 시작 버튼을 클릭하면 데이터가 CollectionVC로 전송됩니다 (데이터가 올바른지 확인하기 위해 중단 점을 사용했습니다).하지만 Segue 후에 데이터가 다시 초기화되고 CollectionView를 빌드 할 데이터가 없습니다. . 현재이 문제를 해결하는 방법을 모르겠습니다.어떤 VC에 viewDidLoad 메서드가 포함되어 있는지 명확히하기 위해? 두 VC에서 모두 시도했지만 문제를 해결하지 못하는 것 같습니다. – Bepa1012

관련 문제