Swift detecting where a touch occurs in draw:

Apologies in advance this is my first time posting a question and I am a beginner to this language but have scraped the forums and documentation already;

type of drawing I would like to create, click to view

enter image description here

If I was to create a graph similar to the photo attached, is there a way I can execute a function based on what segment that was tapped.

Is there a way to add sender tags to shapes created in draw, Such as

// In custom drawing class
override func draw(_ rect: CGRect) {
    let shape1 = UIBezierPath() // code for segment 1
    let shape2 = UIBezierPath() // code for segment 2
    let shape3 = UIBezierPath() // code for segment 3
    // etc, etc
    shape1.tag = 1
    shape2.tag = 2
    shape3.tag = 3
    // etc
}

// In ViewController.swift
@IBAction func shapeButtonFunction(_ shape: Any) {
    if shape.tag == 0 {
        // do this
    }
    else if shpae.tag == 1 {
        // do this
    }
}

In essence, can I create closed shapes and determine when they were tapped through the use of some kind of tag that can be recognised.

Thank you so much for any help in advance !

1 answer

  • answered 2018-07-11 08:52 Satachito

    UIBezierPath has 'contains' method.

    func contains(_ point: CGPoint) -> Bool

    So, save your shapes and test hit using this method inside touchesBegan or touchesEnded.

    class   SomeV: UIView {
        var shape1 = UIBezierPath()
        var shape2 = UIBezierPath()
        var shape3 = UIBezierPath()
        override func draw(_ rect: CGRect) {
            shape1 = UIBezierPath() // code for segment 1
            shape2 = UIBezierPath() // code for segment 2
            shape3 = UIBezierPath() // code for segment 3
            // etc
        }
        override func
        touchesEnded( _ touches: Set<UITouch>, with event: UIEvent? ) {
            if let w = touches.first?.location( in: self ) {
                if shape1.contains( w ) { print( "Touches in shape1" ) }
                if shape2.contains( w ) { print( "Touches in shape1" ) }
                if shape3.contains( w ) { print( "Touches in shape1" ) }
            }
        }
    }