我想只重新加载选定的单元格,特别是在单元格中点击图片时。但是我得到的错误是无法在此行将类型'IndexPath.Type'的值转换为预期的参数类型'IndexPath':loadPostsValue(indexPath :IndexPath)
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let indexPath = self.collectionView.indexPathsForSelectedItems
print(indexPath)
loadPostsValue(indexPath: IndexPath)
}
func loadPostsValue(indexPath: IndexPath) {
posts.removeAll()
let ref = Database.database().reference()
ref.child("posts").observe(.childAdded) { (snapshot: DataSnapshot) in
if let dict = snapshot.value as? [String: Any] {
guard let titleText = dict["title"] as? String else{return}
let locationDetails = dict["location"] as! String
let captionText = dict["caption"] as! String
let photoUrlString = dict["photoUrl"] as! String
let priceText = dict["price"] as! String
let categoryText = dict["category"] as! String
let usernameLabel = dict["username"] as! String
let profileImageURL = dict["pic"] as! String
let heartInt = dict["heart"] as! Int
let timestampString = dict["timestamp"] as! String
let post = Post(titleText: titleText, captionText: captionText, locationDetails: locationDetails, photoUrlString: photoUrlString, priceText: priceText,categoryText: categoryText, usernameLabel: usernameLabel, profileImageURL: profileImageURL, heartInt: heartInt, timestampString: timestampString)
self.posts.append(post)
print(self.posts)
self.collectionView.reloadItems(at: [indexPath])
}
}
}
答案 0 :(得分:0)
您应按如下所示提供所需的indexPath
,
if let indexPath = self.collectionView.indexPathsForSelectedItems?.first {
print(indexPath)
loadPostsValue(indexPath: indexPath)
}
当前,您没有传递IndexPath
的对象,而是传递了Type
抱怨的compiler
的对象。另外,indexPathsForSelectedItems
是所有选定项的array
,因此如果您的indexPath
的多项选择已关闭,则应该检索第一个collectionView
。
编辑,我认为一种简单的方法是当您已经从委托方法本身中选择了indexPathsForSelectedItems
时不使用indexPath
。您只需将其传递如下,
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
loadPostsValue(indexPath: indexPath)
}
正如您在评论中提到的那样,我认为如果您只想更新点赞次数,可以按以下步骤操作
func loadPostsValue(indexPath: IndexPath) {
let ref = Database.database().reference()
ref.child("posts").observe(.childAdded) { (snapshot: DataSnapshot) in
if let dict = snapshot.value as? [String: Any] {
guard let titleText = dict["title"] as? String else{ return }
let post = self.posts[indexPath.row]
post.heartInt = dict["heart"] as! Int
self.collectionView.reloadItems(at: [indexPath])
}
}
}