-1

I would like to define a clickable zone in a picture for an iOS Project. It seems like "Where's Wally". When I clicked in a specific zone, Swift do this action. There are the swipe to manage too. I thought to make a transparent button but I don't know if it's possible..

Have you any ideas ?

Thank's ! :-)

Romain
  • 53
  • 1
  • 6

1 Answers1

1

For iOS, you can do it this way:

(1) Remember to set your UIImageView to receive user interactions, and add a UITapGestureRecognizer to the UIImageView.

myImageView.isUserInteractionEnabled = true
let tapGesture = UITapGestureRecognizer()
tapGesture.numberOfTapsRequired = 1
tapGesture.addTarget(self, action: #selector(tapDetected())

(2) Create a new CALayer, size it, position it, and add it to the UIImageView's layer.

let tappableLayer = CALayer() // place this as a global variable

tappableLayer.frame = // give a CGRect size here, or you can make it a shape by declaring a UIBezierPath and making it a CAShapeLayer
myImageView.layer.addSublayer(tappableLayer)

(3) Code the tapDetected function.

func tapDetected(_ recognizer:UITapGestureRecognizer) {
    let p = recognizer.location(in: self)
    if tappableLayer.hitTest(p) != nil {
        // user tapped in your defined area of the image
    }
}
  • Nice answer. I was first wondering why you use a CALayer and not simply a CGRect, but having the possibility to use the different shapes for the `hitTest` is amazing! – kiecodes Feb 07 '17 at 15:50
  • The hitTest() method belongs to *all* CALayers. If you simply turned it on for the myImageView layer, you'd detect the entire view. so the other reason I didn't just use a CGRect was because that doesn't have a hitTest() method. –  Feb 07 '17 at 15:55
  • 1. I don't see how this relates to my compliment about your answer, but true story! :) 2. One could use `CGRectContainsPoint` for that, i guess. – kiecodes Feb 07 '17 at 16:01
  • 1
    I never knew that! My needs for using CALayers is because I need to resize/move/rotate them. I learned something from you today. :-) –  Feb 07 '17 at 16:03