Detecting a tap on a CAShapeLayer in Swift?

前端 未结 4 561
时光取名叫无心
时光取名叫无心 2020-12-29 13:18

I\'m quite new to iOS Development (so please forgive my ineptitude - I\'ve looked everywhere!), and was looking to find a way to detect a tap on a CAShapeLayer.

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-29 13:50

    Heres imo the best way to do what you want to achieve:

    // First add the shapelayer
    let layer = CAShapeLayer()
    layer.anchorPoint = CGPointZero
    layer.path = UIBezierPath(ovalInRect: CGRect(x: 0, y: 0, width: 100, height: 200)).CGPath
    layer.bounds = CGPathGetBoundingBox(layer.path) // IMPORTANT, without this hitTest wont work
    layer.fillColor = UIColor.redColor().CGColor
    self.view.layer.addSublayer(layer)
    
    
    // Check for touches
    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        let point = touches.anyObject()!.locationInView(self.view) // Where you pressed
    
        if let layer = self.view.layer.hitTest(point) as? CAShapeLayer { // If you hit a layer and if its a Shapelayer
            if CGPathContainsPoint(layer.path, nil, point, false) { // Optional, if you are inside its content path
                println("Hit shapeLayer") // Do something
            }
        }
    }
    

提交回复
热议问题