2017-09-15 63 views
1

我一直在試圖實現一個集合視圖,其中用戶可以像一個帖子,但由於某種原因,當用戶這樣做時,它會更新提要,但只是雙倍的單元格數量和留下應該消失的舊細胞。總之,一半的細胞被更新,另一半是舊的值。基本上我不知道如何簡單地更新當前的單元格,而沒有問題。理想情況下,我希望用戶按下類似按鈕,除了該按鈕轉到「不像」以及要在collectionview中更改的帖子上的喜好數量外,沒有別的事情會發生。UICollectionView重新加載單元但不刪除舊單元

下面是加載集合視圖單元代碼:

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 
} 
+0

你在哪裏重新加載集合視圖? – ebby94

+0

@ ebby94我正在加載帖子的函數末尾重新加載收藏視圖。此函數在viewwillappear中調用 – dombad

回答

0

對於喜歡,我建議您使用的是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 

       // ... 

    }) 

} 

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

我們知道用戶是否喜歡的文章或沒有,你可以在你的類中創建一個布爾本地保存的樣態:

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。

只要告訴我,如果您有任何問題!

相關問題