Swift 3 iOS -Override HitTest不让SubView接收触控超出它的SuperView的界限

时间:2017-06-20 08:13:04

标签: button view cgrect bounds touches

enter image description here

我有一个collectionView单元格,它有一个来自StoryBoard的imageView和一个以编程方式添加的deleteButton(红色X),它超出了单元格的边界x:-12, y:-18。我试图覆盖hitTest以接收单元格范围之外的触摸,但它不起作用。但是,当它(或其任何部分)在单元格范围内时,我能够触发按钮上的事件。在storyboard的imageView中我检查了isUserIneractionEnabled并且在单元格类中我在deleteButton和单元格本身上启用了它。我在单元格和imageView上也有clipsToBounds = false。

我注意到,当我打印出我的子视图时,唯一可以打印的视图是imageView。也许这就是问题?

以下是代码:

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;
    }

为什么我不能接受触摸事件虽然我已经覆盖了hitTest?

0 个答案:

没有答案