2

enter image description here

I have a collectionView cell that has an imageView from StoryBoard and a deleteButton (the red X) added programmatically that extends beyond the cell's bounds x:-12, y:-18. I tried to override the hitTest to receive touches outside the cell's bounds but it doesn't work. However I am able to trigger events on the button when it (or any part of it) is within the cell's bounds. On the imageView in storyboard's I have isUserIneractionEnabled checked and inside the cell class I have it enabled on the deleteButton and cell itself. I also have clipsToBounds = false on the cell and imageView.

I did notice that as I printed out my subviews the only view that gets printed is the imageView. Maybe that's the problem?

Here's the code:

class MyCell: UICollectionViewCell {

    @IBOutlet weak var imageView: UIImageView!

    var deleteButton: UIButton!
    var deleteButtonImg: UIImage!

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        deleteButton = UIButton(frame: CGRect(x: -12, y: -18, width: frame.size.width/4, height: frame.size.width/4))

        deleteButtonImg = UIImage(named: "red-x")!
        deleteButton.setImage(deleteButtonImg, for: .normal)

        self.isUserInteractionEnabled = true
        deleteButton.isUserInteractionEnabled = true
        contentView.addSubview(deleteButton)
    }

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        if (!self.clipsToBounds && !self.isHidden && self.alpha > 0.0) {

            for view in self.subviews.reversed() {
                print(".......\(subviews.description)")
                let subPoint = view.convert(point, from: self)
                let result = view.hitTest(subPoint, with: event)

                if (result != nil){
                    return result
                }
            }
        }
        return nil;
    }

Why cannot I not receive touches event though I'm overriding the hitTest?

Lance Samaria
  • 17,576
  • 18
  • 108
  • 256

0 Answers0