[今回聞きたいこと]
・numberOfItemsInSection と、numberOfSections の return の値をどうすればいいでしょうか?
インスタグラムの類似アプリを作っています。
こちらのサイトのコードを、ほぼそのまま使って、CollectionViewのカスタムレイアウトを実装しています。
https://swiswiswift.com/2017/11/26/custum-collectionview/
今回実装しているcollectionViewのレイアウトはこの画像と同じものです。
CustomCollectionViewFlowLayoutクラスを、コレクションビューにアタッチしています。
コードはこちらのページのCustomCollectionViewFlowLayoutクラスのコードと全く同じです。
firebaseから引っ張ってきたデータ(今回の場合だとpostオブジェクトの中に入っている画像url)をコレクションビューに表示させたいです。
データーを一つ取ってくるごとに、collectionViewがreloadData()されるようになっています。
numberOfItemsInSection と、numberOfSections の return の値をどのように変えれば、outofindexなどのエラーを出さずに表示させることができるでしょうか?
Swift
1import UIKit 2import SDWebImage 3import FirebaseDatabase 4 5class DiscoverViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { 6 7 @IBOutlet weak var myCollectionView: UICollectionView! 8 var REF_POSTS = Database.database().reference().child("posts") 9 var posts: [Post] = [] 10 11 override func viewDidLoad() { 12 super.viewDidLoad() 13 myCollectionView.delegate = self 14 myCollectionView.dataSource = self 15 16 loadTopPosts() 17 } 18 19 func loadTopPosts() { 20 21 REF_POSTS.queryOrdered(byChild: "timestamp").observeSingleEvent(of: .value, with: { snapshot in 22 let arraySnapshot = (snapshot.children.allObjects as! [DataSnapshot]).reversed() 23 arraySnapshot.forEach({ (child) in 24 if let dict = child.value as? [String: Any] { 25 let post = Post.transformPostPhoto(dict: dict, key: child.key) 26 self.posts.append(post) 27 self.myCollectionView.reloadData() 28 } 29 }) 30 } 31 } 32 33 //Cellが選択された際に呼び出される 34 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 35 print("Section: (indexPath.section)") 36 print("Num: (indexPath.row)") 37 print("Number: (indexPath.section * 6 + indexPath.row)") 38 } 39 40 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 41 42 return 6 //←ここの値を変える 43 44 } 45 //セクションの総数を返す 46 func numberOfSections(in collectionView: UICollectionView) -> Int { 47 return 8 //←ここの値を変える 48 } 49 50 //Cellに値を設定する 51 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 52 53 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! CustomCollectionViewCell 54 55 56 57 let photoUrlString = self.posts[indexPath.section * 6 + indexPath.row].imageUrls[0] //←エラー 58 let photoUrl = URL(string: photoUrlString) 59 cell.imageView1.sd_setImage(with: photoUrl) 60 61 62 63 return cell 64 } 65}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/05/30 22:35