Swift UICollectionView单元格内的按钮赢得';不要触发动作,什么都不起作用

Swift UICollectionView单元格内的按钮赢得';不要触发动作,什么都不起作用,swift,uicollectionview,Swift,Uicollectionview,我在CollectionView单元中有三个UIButtons,点击按钮时触摸动作不会触发。我尝试了一些解决方案,但没有一个对我有效。 这就是我到目前为止所做的: protocol PostCellDelegate { func handleDeletePost() func handleUpvotePost() func handleDownvotePost() } class PostCell: UICollectionViewCell { var del

我在CollectionView单元中有三个UIButtons,点击按钮时触摸动作不会触发。我尝试了一些解决方案,但没有一个对我有效。 这就是我到目前为止所做的:

protocol PostCellDelegate {
    func handleDeletePost()
    func handleUpvotePost()
    func handleDownvotePost()
}

class PostCell: UICollectionViewCell {

    var delegate: PostCellDelegate?

    lazy var buttons = [self.deletePostBtn, self.upvotePostBtn, self.downvotePostBtn]

    @objc func handleDeletePost(){
        delegate?.handleDeletePost()
    }

    @objc func handleUpvotePost(){
        delegate?.handleUpvotePost()
    }

    @objc func handleDownvotePost(){
        delegate?.handleDownvotePost()
    }

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        guard isUserInteractionEnabled else { return nil }
        guard !isHidden else { return nil }
        guard alpha >= 0.1 else { return nil }

        guard self.point(inside: point, with: event) else { return nil }

        for button in buttons {
            if button.point(inside: convert(point, to: button), with: event){
                return button
            }
        }
        return super.hitTest(point, with: event)
    }

}
在hitTest中,它确实获得了我想要的按钮(每个按钮)并返回它,但操作不会触发

这是我的HomeVC(CollectionViewController):

CellForItem:

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PostCell
    let post = posts[indexPath.row]
    cell.postTitle.text = post.title

    return cell
}
我就是没办法让这个按钮启动。无论我尝试了什么解决方案,它都不会触发它的行动。
有什么想法吗?

您需要在创建单元格时设置代理

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PostCell
    let post = posts[indexPath.row]
    cell.postTitle.text = post.title
    cell.delegate = self  // You're missing this
    return cell
}

您需要在退出单元格时设置代理,例如cell.delegate=self谢谢,我今天会再试一次,现在我注意到我没有在正确的位置编写它。您在哪里为按钮添加了操作?在PostCell中,在CollectionVC中设置它们,但我会再次尝试JonJ所说的,然后查看。
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PostCell
    let post = posts[indexPath.row]
    cell.postTitle.text = post.title
    cell.delegate = self  // You're missing this
    return cell
}