Search code examples
iosswiftuiviewcore-graphics

Detecting long press in list of CAShapeLayer


I have a list of objects that have a visible CAShapeLayer on my view.

internal class Line {
    var layer = CAShapeLayer()
}

These are displayed on an object of type UIView. On the UIView I have a longPress gesture recognizer which should detect a long press on one of the line.layers.

This is what I got

@objc private func didLongPress(_ sender: UILongPressGestureRecognizer) {
    var selectedLine: Line?
    let touchPoint = sender.location(in: self)
    if sender.state == .began {
        for line in lines {
            if line.layer.contains(touchPoint) == true {
                print("true")
            } else {
                print("false")
            }

        }
    } else if sender.state == .changed {
        for line in lines {
            if line.layer.contains(touchPoint) == true {
                print("true")
            } else {
                print("false")
            }

        }

    } else if sender.state == .ended {
        for line in lines {
            if line.layer.contains(touchPoint) == true {
                print("true")
            } else {
                print("false")
            }

        }

    }
}

Needless to say, it only prints false. Does anyone have any idea?

Thanks!


Solution

  • Found the solution in:

    line.layer.path?.boundingBox.contains(touchPoint)