我的逻辑很简单:我想构建一个像Instagram这样的应用程序。对于“ Feed / Main”页面,我正在使用具有自定义布局(例如Pinterest)的UICollection View。
[我的第一个想法是获取帖子。我的fetchPosts()函数是
func fetchPosts(){
// Temporaly just fetch all posts.
// guard let currentUid = Auth.auth().currentUser?.uid else {return}
POSTS_REF.observeSingleEvent(of: .value) { (snapshot) in
guard let dictionary = snapshot.value as? Dictionary<String,AnyObject> else {return}
for fetchedPost in dictionary{
let postId = fetchedPost.key
let postDictionary = fetchedPost.value as! Dictionary<String,AnyObject>
guard let userId = postDictionary["userId"] else {return}
self.fetchUser(withUid: userId as! String) { (user) in
let postImageUrl = postDictionary["photoUrl"] as! String
self.loadImage(with: postImageUrl) { (image) in
let post = Post(createdBy: user, postId: postId, image: image, dictionary: postDictionary)
CONSTANT_FeedCollectionVC?.posts.append(post)
DispatchQueue.main.async {
CONSTANT_FeedCollectionVC?.collectionView.reloadData()
}
}
}
}
}
}
但是我的问题是在我成功推送新帖子并返回到Feed页面之后。从打印日志信息来看,项目的数量确实增加了一,但是indexPath.row却没有增加。例如,我现在有3个帖子,index.row停在0,1和2在哪里?即使我重新运行该应用程序,仍然只能得到一个帖子。我确定我有3个帖子,因为我在Firebase网站面板上检查了它。
我尝试如下打印项目数,索引路径和帖子数组数,但结果显示数:0数:1索引:0帖子数:2数:3索引:0帖子数:3
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print("count:",posts.count)
return posts.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
print("Index: ",indexPath.row," Posts count: ",posts.count)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! FeedCollectionCell
// The delegate should
cell.delegate = self
cell.post = posts[indexPath.row]
cell.addShadow()
cell.layer.cornerRadius = 8
return cell
}
我有3个帖子,但Index.row停止为0 ?!我在FirebaseService类中编写了fetchPost()函数,并在FeedViewController中对其进行了调用。 CONSTANT_FeedCollectionVC只是一个常量“ var CONSTANT_FeedCollectionVC:FeedCollectionVC?”。
class FeedCollectionVC: UICollectionViewController {
var posts = [Post]()
override func viewDidLoad() {
super.viewDidLoad()
CONSTANT_FeedCollectionVC = self
if let layout = collectionView?.collectionViewLayout as? MyLayoutForFeed {
layout.delegate = self
}
self.collectionView.alwaysBounceVertical = true
FirebaseService.shared.fetchPosts()
}
请先把我从这里救出来,谢谢。
您的posts.count
在增加,这意味着您的模型正在更新。但是,cellForItemAt
仅针对可见行被调用。除非将它们滚动到视图中,否则您不应看到它需要单元格1和2。
因此,发生了两件事之一:
也许只有indexPath.item
为0的单元格当前可见(例如,这是一个全屏单元格,其中单元格1和2尚不可见吗?)。在将这些单元格滚动到视图中之前,不要期望看到1或2的indexPath.item
。
如果单元格1和2应该可见,但您没有看到要求这些单元格的cellForItemAt
,则您的自定义MyLayoutForFeed
可能有问题。如果这不是一个简单的流布局子类,而是一个完全自定义的UICollectionViewLayout
,则其layoutAttributesForElements(in:)
将决定它认为在layoutAttributesForElements(in:)
中可见的单元格。 CGRect
中可能无法正确识别应显示单元格1和2。