每次按此按钮时,集合查看单元格重复(Swift)

时间:2017-10-17 21:44:20

标签: ios iphone swift xcode uicollectionview

每次点击相似按钮(心形图标)时,单元格都会更新,但它也会重复。我研究并试图自己解决这个问题,但我不知道为什么它会被重复。

我调查过,我发现可能这可能是cellForRowAtIndexPath函数的一个问题,但该函数对我来说很好看。

以下是相关代码:

HomeController.swift:

class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout, HomePostCellDelegate {

let cellId = "cellId"

override func viewDidLoad() {
    super.viewDidLoad()

    collectionView?.register(HomePostCell.self, forCellWithReuseIdentifier: cellId)


    let refreshControll = UIRefreshControl()
    refreshControll.addTarget(self, action: #selector(handleRefresh), for: .valueChanged)
    if #available(iOS 10.0, *) {
        collectionView?.refreshControl = refreshControll
    } else {
        // Fallback on earlier versions
    }
    setupNavigationItems()
    fetchAllPost()
}

@objc func handleUpdateFeed() {
    handleRefresh()
}

@objc func handleRefresh() {
    posts.removeAll()
    fetchAllPost()
}

fileprivate func fetchAllPost() {
    fetchPosts()
    fetchFollowingUserIds()
}

fileprivate func fetchFollowingUserIds() {
    guard let uid = FIRAuth.auth()?.currentUser?.uid else { return }
    FIRDatabase.database().reference().child("following").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in

        guard let userIdsDictionary = snapshot.value as? [String: Any] else { return }
        userIdsDictionary.forEach({ (key,  value) in
            FIRDatabase.fetchUserWithUid(uid: key, completion: { (user) in
                self.fetchPostsWithUser(user: user)
            })
        })
    }) { (err) in
        print("failed to fetch following users ids:", err)
    }
}

var posts = [Post]()
fileprivate func fetchPosts() {
    guard let currentUserID = FIRAuth.auth()?.currentUser?.uid else { return }
    FIRDatabase.fetchUserWithUid(uid: currentUserID) { (user) in
        self.fetchPostsWithUser(user: user)
    }
}
fileprivate func fetchPostsWithUser(user: User) {
    let ref = FIRDatabase.database().reference().child("posts/\(user.uid)/")

    ref.observeSingleEvent(of: .value, with: { (snapshot) in

        if #available(iOS 10.0, *) {
            self.collectionView?.refreshControl?.endRefreshing()
        } else {
            // Fallback on earlier versions

        }

        guard let dictionaries = snapshot.value as? [String: Any] else { return }
        dictionaries.forEach({ (key,value) in

            guard let dictionary = value as? [String: Any] else { return }
            var post = Post(user: user, dictionary: dictionary)
            post.id = key
            guard let uid = FIRAuth.auth()?.currentUser?.uid else { return }
            FIRDatabase.database().reference().child("likes").child(key).child(uid).observe(.value, with: { (snapshot) in
                if let value = snapshot.value as? Int, value == 1 {
                    post.hasLiked = true
                } else {
                    post.hasLiked = false
                }

                self.posts.append(post)

                self.posts.sort(by: { (p1, p2) -> Bool in
                    return p1.creationDate.compare(p2.creationDate) == .orderedDescending
                })
                self.collectionView?.reloadData()
                print("fetch post with user reload data")
            }, withCancel: { (err) in
                print("Failed to fetch info for post")
            })
        })
    }) { (error) in
        print("Failed to fetch posts", error)
    }
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return posts.count
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let height: CGFloat = 310 // username + userProfileImageView
    return CGSize(width: view.frame.width - 27.5, height: height)
}


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

    cell.post = posts[indexPath.item]
    cell.delegate = self
    cell.photoImageView.image = nil
    // Makes cell corners round
    cell.layer.masksToBounds = true
    cell.layer.cornerRadius = 17
    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 20
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 5
}

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
        }
        print("Successfully liked post!")

        post.hasLiked = !post.hasLiked

        self.posts[indexPath.item] = post

        self.collectionView?.reloadItems(at: [indexPath])

    }
 }
}

如果您有任何疑问,请告诉我们,谢谢!

0 个答案:

没有答案