簡體   English   中英

UICollectionView重新加載單元格,但不刪除舊單元格

[英]UICollectionView Reloading cells but not deleting old ones

我一直在嘗試實現一個收集視圖,在該視圖中,用戶可以喜歡帖子,但是由於某種原因,當用戶這樣做時,它會更新提要,但只需將單元格的數量加倍,並保留應刪除的舊單元格。 簡而言之,一半的單元格被更新,另一半是舊值。 基本上,我無法弄清楚如何簡單地更新當前單元而不會出現問題。 理想情況下,我希望用戶按下“贊”按鈕,除了該按鈕變為“不喜歡”並且在collectionview中更改帖子的喜歡數之外,什么都不會發生。

以下是用於加載集合視圖單元格的代碼:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = feedCollectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! MyGroupFeedCollectionViewCell

    cell.postKey = feedArray[indexPath.row].postKey

    //clears the cells first
    cell.profileImage.image = nil
    cell.usernameLabel.text = nil
    cell.usernameLabel2.text = nil
    cell.groupName.text = nil
    cell.postImageView.image = nil
    cell.postCaptionTextView.text = nil
    cell.timeStamp.text = nil

    //load profile picture
    cell.profileImage.sd_setImage(with: URL(string: feedArray[indexPath.row].ProfilePic), placeholderImage: UIImage(named:"no profile picture.png"))

    //load username
    cell.usernameLabel.text = feedArray[indexPath.row].Username
    cell.usernameLabel2.text = feedArray[indexPath.row].Username

    //load groupName when in home feed
    cell.groupName.text = feedArray[indexPath.row].GroupName

    //load postImage
    cell.postImageView.sd_setImage(with: URL(string: feedArray[indexPath.row].PostImage), placeholderImage: UIImage(named:"penguinPanorama"))

    //load caption
    cell.postCaptionTextView.text = feedArray[indexPath.row].caption

    //load likes once likes are implemented
    //checks if the user has liked the post or not
    databaseRef.child("likes").child((FIRAuth.auth()?.currentUser?.uid)!).child(feedArray[indexPath.row].postKey).observe(.value, with: { (snapshot) in
        if(snapshot.exists())
        {
            cell.liked = "Yes"
            cell.likeButton.setTitle("Unlike", for: .normal)
        }
        else{
            cell.liked = "No"
            cell.likeButton.setTitle("Like", for: .normal)
        }
    })

這是按下“贊”按鈕的功能代碼:

@IBAction func likeButton_tapped(_ sender: Any) {
    self.likeButton.isEnabled = false
    print(self.postKey)
    print(self.liked)

    //make it so liking or unliking adds or subtracts from the total number of likes on the post
    if liked == "Yes"
    {
         self.databaseRef.child("likes").child((FIRAuth.auth()?.currentUser?.uid)!).child(self.postKey).removeValue()

        let NewLikeNumber = likeNumber - 1
        self.databaseRef.child("GroupPosts").child(self.groupName.text!).child(self.postKey).child("likes").setValue(NewLikeNumber)
        print(NewLikeNumber)
    }
    else{
        self.databaseRef.child("likes").child((FIRAuth.auth()?.currentUser?.uid)!).child(self.postKey).setValue("")

        let NewLikeNumber = likeNumber + 1
        self.databaseRef.child("GroupPosts").child(self.groupName.text!).child(self.postKey).child("likes").setValue(NewLikeNumber)
        print(NewLikeNumber)
    }

    self.likeButton.isEnabled = true
}

對於喜歡的人,我建議您使用Firebase事務,因為由於並發修改,您的喜歡數最終可能會變得一團糟:

 func likePost(_ post: Post, completion: @escaping () -> ()) {

    guard let currentUserId = Auth.auth().currentUser?.uid else {
       return
    }

    databaseRef.child(likes).child(currentUserId).child(postKey).runTransactionBlock ( { (currentData: MutableData) -> TransactionResult in

              if var data = currentData.value as? [String: Any] {
                  var count = data["likesCount"] as! Int
                  count += 1
                  data["likesCount"] = count
                  currentData.value = data
                  return TransactionResult.success(withValue: currentData)
              }

              return TransactionResult.success(withValue: currentData)

     }, andCompletionBlock: { (error, success, snapshot) in

                // ...

     })

}

當然,對於不喜歡帖子的用戶也是如此。

現在要知道用戶是否喜歡該帖子,您可以在您的類中創建一個布爾值以將like狀態保存在本地:

private var isPostLiked = false

並且每當用戶點擊“贊”按鈕時,都應進行如下簡單檢查:

     func handleLikeTapped() {

            guard let post = post else {
                return
            }

            if isPostLiked {

                NetworkManager.shared.likePost(post, completion: { [weak self] in

                    // Once the completion handler of your method is called, the likes count in your database is now updated. 
                    // To avoid making another read in the database just now, you can just
                    // Update your count (a label that shows how many likes a specific post received I guess ?) locally here so that the user can see in realtime the change (with animation or not depending on what you want to achieve)

                    // And finally update the like state of the post so that if the user click again on like it wouldn't mess everything up:

                    self?.isPostLiked = false
                })

            }

            else {

                NetworkManager.shared.dislikePost(post, completion: { [weak self] in

                    // ...
                })
            }
   }

當然,現在稍后,如果您需要在其他視圖控制器中訪問“喜歡”計數,則只需使用observeSingleEvent(of: .value)從數據庫中獲取更新的likesCount。

如果您有任何疑問,請隨時告訴我!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM