我正在尝试为我正在处理的应用程序提供两个UICollectionViews。我可以得到一个,由Firebase填充以显示(imageCollection)。不幸的是,我无法让第二个出现(popImageCollection)。我的所有商店都在那里。我不确定我到底做错了什么。
这是我的视图控制器:
import UIKit
import Firebase
import FirebaseDatabase
import SDWebImage
class ViewController: UIViewController, UICollectionViewDataSource {
@IBOutlet weak var popImageCollection: UICollectionView!
@IBOutlet weak var imageCollection: UICollectionView!
var customImageFlowLayout = CustomImageFlowLayout()
var images = [BlogInsta]()
var popImageArray = [UIImage]()
var dbRef: DatabaseReference!
var dbPopularRef: DatabaseReference!
override func viewDidLoad() {
super.viewDidLoad()
dbRef = Database.database().reference().child("images")
dbPopularRef = Database.database().reference().child("popular")
loadDB()
loadImages()
customImageFlowLayout = CustomImageFlowLayout()
imageCollection.backgroundColor = .white
popImageCollection.delegate = self as? UICollectionViewDelegate
popImageCollection.dataSource = self
imageCollection.delegate = self as? UICollectionViewDelegate
imageCollection.dataSource = self
self.view.addSubview(popImageCollection)
self.view.addSubview(imageCollection)
}
func loadImages() {
popImageArray.append(UIImage(named: "1")!)
self.popImageCollection.reloadData()
}
func loadDB() {
dbRef.observe(DataEventType.value, with: { (snapshot) in
var newImages = [BlogInsta]()
for BlogInstaSnapshot in snapshot.children {
let blogInstaObject = BlogInsta(snapshot: BlogInstaSnapshot as! DataSnapshot)
newImages.append(blogInstaObject)
}
self.images = newImages
self.imageCollection.reloadData()
})
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == self.imageCollection {
let cell = imageCollection.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ImageCollectionViewCell
let image = images[indexPath.row]
cell.imageView.sd_setImage(with: URL(string: image.url), placeholderImage: UIImage(named: "1"))
return cell
} else {
let cellB = popImageCollection.dequeueReusableCell(withReuseIdentifier: "popCell", for: indexPath) as! PopularCollectionViewCell
let popPhotos = popImageArray[indexPath.row]
cellB.popularImageView.image = popPhotos
return cellB
}
}
}
答案 0 :(得分:0)
如果集合在IB中,请不要再次添加
self.view.addSubview(popImageCollection) // remove
self.view.addSubview(imageCollection) // remove
另外
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == self.imageCollection {
return images.count
}
else {
return popImageArray.count
}
}
//
委托应该在类声明中,因为不要在运行时设置为nil
class ViewController: UIViewController, UICollectionViewDataSource , UICollectionViewDelegate {