【发布时间】:2021-04-03 01:25:30
【问题描述】:
我的UICollectionView 没有显示数据,我做错了什么?
这里是集合视图控制器类:
class SongfeedViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {
@IBOutlet weak var collectionview: UICollectionView!
var posts = [Post]()
private var song = [songs]()
private var songsCollection : CollectionReference!
override func viewDidLoad() {
super.viewDidLoad()
songsCollection = Firestore.firestore().collection("Songs")
}
override func viewWillAppear(_ animated: Bool)
{
songsCollection.getDocuments { (snapshot, error) in
if let err = error{
print("Error Fetching Docs:\(err)")
} else {
guard let snap = snapshot else{return}
for document in snap.documents{
let data = document.data()
let fullname = data["fullname"] as? String ?? "Anonymous"
let songname = data["songname"] as? String ?? "Anonymous"
let youtubelink = data["youtubelink"] as? String ?? "Anonymous"
let moneyoffer = data["moneyoffer"] as? String ?? "Anonymous"
let instalink = data["instalink"] as? String ?? "Anonymous"
let newsong = songs(fullname: fullname, songname: songname, moneyoffer: moneyoffer, youtubelink: youtubelink, instalink: instalink)
self.song.append(newsong)
}
self.collectionview.reloadData()
}
}
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.posts.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionview.dequeueReusableCell(withReuseIdentifier: "postCell", for: indexPath) as! postCell
cell.artistnamelabel.text = self.posts[indexPath.row].fullname
cell.moneyofferlabel.text = self.posts[indexPath.row].moneyoffer
cell.instaUsernnamelabel.text = self.posts[indexPath.row].instalink
cell.songnamelabel.text = self.posts[indexPath.row].songname
cell.youtubelinklabel.text = self.posts[indexPath.row].youtubelink
return cell
}
来自 firestore 的数据未显示在 UI 集合视图上。
我的邮箱中的代码如下:
import UIKit
class postCell: UICollectionViewCell {
@IBOutlet weak var artistnamelabel: UITextField!
@IBOutlet weak var moneyofferlabel: UITextField!
@IBOutlet weak var songnamelabel: UITextField!
@IBOutlet weak var youtubelinklabel: UITextField!
@IBOutlet weak var instaUsernnamelabel: UITextField!
}
【问题讨论】:
-
答案中提到了这一点,但这更像是一个错字。在委托函数
collectionView:numberOfItemsInSection中,此代码return self.posts.count将始终返回0,因为该数组中没有添加任何内容。例如self.posts 已初始化var posts = [Post]()但从未填充数据。
标签: swift xcode firebase google-cloud-firestore storyboard