我在CollectionView单元内有三个UIButton,点击按钮时,触摸动作不会触发。我尝试了几种解决方案,但对我没有任何帮助。 这是我到目前为止的内容:
libssl-devel
在hitTest中,它确实获得了我想要的按钮(每个按钮之一)并返回了它,但操作不会触发。
这是我的HomeVC(CollectionViewController):
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)
}
}
CellForItem:
//MARK: Button handlers
extension HomeVC: PostCellDelegate {
func handleUpvotePost() {
print("TEST")
}
func handleDownvotePost() {
print("TEST")
}
func handleDeletePost() {
print("TEST")
}
}
我根本无法按下按钮来工作。无论我尝试了哪种解决方案,它都不会触发它的动作。 有什么想法吗?
答案 0 :(得分:0)
在创建单元格时需要设置委托。
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
}