lofdev
lofdev

Reputation: 1

Identifying a CALayer on Touch Event (porting functional code to Swift)

I'm porting one of my own code snippets from Objective-C to Swift, partially as a learning exercise and partially because I am starting a new app.

I have created a CALayer-derived class, which contains an array of sublayer CALayers. I am using this as an expanding menu of icons. The Obj-C repository is here if that helps: https://github.com/lofdev/AnimatedIconDrawer.

An instance of the class is embedded in a UIViewController, and in Objective-C, I use this to call the instance, referencing the child sublayer, so that I can do fun things to the instance.

 // _drawer is the instance of a CALayer-derived class
    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        if ([touches count] == 1) {
            for (UITouch *touch in touches) {
                CGPoint point = [touch locationInView:[touch view]];
                point = [[touch view] convertPoint:point toView:nil];
                CALayer *layer = [(CALayer *)self.view.layer.presentationLayer hitTest:point];

                NSInteger clicked_item = [_drawer toggleOpenCloseWithTappedLayer:layer];
            }
        }
    }

Anyway, I have ported the code to Swift, and I appear to be getting incorrect object references. Here's the ported code.

 override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        if touches.count > 0 {
            NSLog("Got a touch.")
        }
        for touch in touches {
            let point = touch.locationInView(touch.view)
            let point_view = touch.view?.convertPoint(point, toView: nil)

        //  This line does not work properly... my guess
            let point_layer = CALayer(layer: view.layer.presentationLayer()!).hitTest(point_view!)

            let clicked_item = drawer.toggleOpenCloseWithTappedLayer(point_layer!)
        }
    }

I assume I'm doing something wrong, but I can't seem to figure it out. Can I assume this is pointer-related.

Any help will be appreciated. And, please be gentle. I'm new to Swift.

Thanks,

Upvotes: 0

Views: 1205

Answers (2)

Pratik Sodha
Pratik Sodha

Reputation: 3727

Swift 5.x

The below solution works for me.

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first
    guard let point = touch?.location(in: view) else {
        return
    }
    
    guard let layer = self.view.layer.hitTest(point) as? CAShapeLayer else {
        return
    }
}

Upvotes: 0

InSearchOf
InSearchOf

Reputation: 170

Try replacing:

let point_layer = CALayer(layer: view.layer.presentationLayer()!).hitTest(point_view!)

With:

let point_layer = CALayer(layer: (self.view.layer.presentationLayer()?.hitTest(point_view!))!)

Late

Upvotes: 1

Related Questions