【发布时间】:2021-10-10 19:41:48
【问题描述】:
我有一个 posts 数组,其中填充了我的数据库中的数据(填充数据发生在 viewDidLoad 中的函数中)。稍后,将使用该数据配置 collectionViewCell。
由于从数据库中获取数据有一点延迟,下面的函数不会返回任何 Int 值。
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return posts.count
}
我已经通过下面的代码在 viewDidLoad 中进行了测试
override func viewDidLoad() {
super.viewDidLoad()
print(posts.count) //TESTED BY PRINTING POSTS.COUNT WHICH IS 0 CURRENTLY
getVideosNamesAndUsers() // The function which gets data from database and updates posts Array
view.addSubview(collectionView)
}
所以我的单元格应该使用来自 posts 数组 的数据进行配置,但是由于在数据来自数据库之前,posts 数组已被初始化。从数据库中下载数据后,它会根据该数据更新 post 数组。
使用下面的代码配置和重新加载单元格,但没有任何反应。我的单元格没有显示。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let postModel = posts[indexPath.row]
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MusicGenresPostsCollectionViewCell().identifier, for: indexPath) as? MusicGenresPostsCollectionViewCell else {
return UICollectionViewCell()
}
self.collectionView = collectionView
cell.configure(with: postModel)
collectionView.reloadData()
return cell
}
注意:我已经注册了单元格并添加了delegate = self 和datasource = self。我的 collectionView 单元仍然没有显示。任何想法将不胜感激。
【问题讨论】:
-
大概,
getVideosNamesAndUsers()是一个异步函数,它“从数据库中获取数据有一点延迟”......在 that 函数中,在您检索数据之后,您需要在您的收藏视图中调用.reloadData()。稍微搜索一下reload collectionview after retrieving data就会给你很多例子、教程、讨论等等。
标签: ios swift uicollectionview uicollectionviewcell