swift
1import UIKit 2import NCMB 3 4class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate{ 5 6 7 @IBOutlet var timescheduleCollectionView: UICollectionView! 8 var subjectArray = [NCMBObject]() 9 10 override func viewDidLoad() { 11 super.viewDidLoad() 12 timescheduleCollectionView.dataSource = self 13 timescheduleCollectionView.delegate = self 14 15 let nib = UINib(nibName: "subjectsCollectionViewCell", bundle: Bundle.main) 16 timescheduleCollectionView.register(nib, forCellWithReuseIdentifier: "Cell") 17 18 let layout = UICollectionViewFlowLayout() 19 layout.itemSize.height = self.view.bounds.height / 9 20 layout.itemSize.width = self.view.bounds.width / 7 21 layout.minimumInteritemSpacing = 0 22 layout.minimumLineSpacing = 0 23 timescheduleCollectionView.collectionViewLayout = layout 24 } 25 26 27 override func viewWillAppear(_ animated: Bool) { 28 super.viewWillAppear(animated) 29 load() 30 } 31 32 33 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 34 self.performSegue(withIdentifier: "register", sender: nil) 35 } 36 37 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 38 return 42 39 } 40 41 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 42 let cell = timescheduleCollectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! subjectsCollectionViewCell 43 print(indexPath.row) 44 return cell 45 } 46 47 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 48 if segue.identifier == "register"{ 49 let AddSubjectsViewController = segue.destination as! AddSubjectsViewController 50 let selectedIndex = timescheduleCollectionView.indexPathsForSelectedItems! 51 AddSubjectsViewController.selectedPath = selectedIndex[0][1] 52 } 53 } 54 55 func load() { 56 let query = NCMBQuery(className: "Subjects") 57 query?.findObjectsInBackground({(result, error) in 58 if error != nil { 59 print(error!) 60 } 61 else { 62 self.subjectArray = result as! [NCMBObject] 63 self.timescheduleCollectionView.reloadData() 64 } 65 }) 66 } 67}
時間割を作成する工程で、collectionviewとNCMBのかけ合わせで作ろとしています。
CollectionViewのセルをタップすると授業名と教室名を登録する画面に遷移し、登録したデータをNCMBに保存し、それを時間割で表示したいと思っています。今、その表示する工程でエラーが発生しています。
内容は以下の通りです。
55行目のfunc load()関数はNCMBに保存してあるデータを取得し、subjectArrayに格納して、CollectionViewをreloadData()で再読み込みをする関数なのですが、時間割を登録したら時間割のページに戻るたびに、データが読み込み、つまり時間割が表示されるようにしたいので、viewWillAppearにload()関数を置くことによって、実現しています。
しかし、load()関数を置くことによって、検証のために設置してある43行目のprint(indexPath.row)が二重に表示されてしまう結果が得られてしまっています。そのせいで、load()関数でCollectionViewを読み込みされていないsubjectArray(つまり空の配列)が出来てしまい、データを表示することが出来ません。解決策をよろしくお願いします。

回答1件
あなたの回答
tips
プレビュー
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
また依頼した内容が修正された場合は、修正依頼を取り消すようにしましょう。
2023/02/13 13:29