某些集合视图单元格中缺少文本标签

时间:2017-12-18 02:35:58

标签: ios swift firebase uicollectionview

问题是某些单元格上缺少文本标签,当我单击like按钮时,文本标签应该更新标签,但整个集合视图会消失。文本标签从firebase获取数字。

Here's a picture of what I mean

以下是相关代码:

HomeController.swift:

n

HomePostCell.swift:

class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout, HomePostCellDelegate {

var hpc: HomePostCell!

let cellId = "cellId"

override func viewDidLoad() {
    super.viewDidLoad()
    collectionView?.register(HomePostCell.self, forCellWithReuseIdentifier: cellId)

}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! HomePostCell
    self.hpc = cell

    cell.post = posts[indexPath.item]
    cell.delegate = self

    return cell
}

@objc func reload(likesLabelNotification: Notification) {

    guard let likesLabel = likesLabelNotification.userInfo?["likesLabelInfo"] as? UILabel else { return }
    guard let indexPath = collectionView?.indexPath(for: hpc) else { return }

    let post = self.posts[indexPath.item]
    guard let postId = post.id else { return }
    let postUserId = post.user.uid

    let numOfLikesRef = FIRDatabase.database().reference().child("likes").child(postId)

    numOfLikesRef.observe(.value, with: { (snapshot: FIRDataSnapshot!) in
        likesLabel.isHidden = false

        let numOfChildrens = snapshot.childrenCount
        likesLabel.text = "\(numOfChildrens)"

    }, withCancel: { (error) in
        print("failed to fetch num of posts: ",error)
    })
    self.posts[indexPath.item] = post

    self.collectionView?.reloadData()
}

func didPressShareButton(for cell: HomePostCell) {

    guard let indexPath = collectionView?.indexPath(for: cell) else { return }

    let post = self.posts[indexPath.item]
    guard let url = NSURL(string: post.videoUrl) else { return }
    let activityViewController = UIActivityViewController(
        activityItems: ["Check out this video I found on Vlogger: \(url)"],applicationActivities: nil)

    present(activityViewController, animated: true, completion: nil)
}

func didLike(for cell: HomePostCell) {

    guard let indexPath = collectionView?.indexPath(for: cell) else { return }

    var post = self.posts[indexPath.item]

    guard let postId = post.id else { return }

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

    let values = [uid : post.hasLiked == true ? 0 : 1]

    FIRDatabase.database().reference().child("likes").child(postId).updateChildValues(values) { (err, _) in
        if let err = err {
            print("Failed to like post", err)
            return
        }

        post.hasLiked = !post.hasLiked

        self.posts[indexPath.item] = post

        self.collectionView?.reloadData()
    }
}

如果您有任何疑问,请在下方发表评论! 提前谢谢!

0 个答案:

没有答案
相关问题