1

In my storyboard I have a few images that are "User Interaction Enabled". In the UIViewController I override the touchesEnded function.

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesEnded(touches, with: event)
}

Is it possible for me to get the name of the image that was clicked in this function? I would prefer not to @IBOutlet the images.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Daniel Åsberg
  • 215
  • 1
  • 2
  • 6
  • Can you explain why you wouldn't like to use IBOutlet for the images? Is the view dynamic, or is the layout the same each time it's displayed? – Stephen Aug 30 '17 at 13:00
  • @stephen Its a mix of static images and dynamic images within a stackview. – Daniel Åsberg Aug 30 '17 at 13:56
  • Check this answer: https://stackoverflow.com/a/5192999/1718685 you should be able to determine the view below the touch. – Stephen Aug 30 '17 at 14:05

2 Answers2

0

I'm fairly certain this is not possible exactly like you want it. Image views don't retain the file they loaded the image from, just the image data itself. But I assume you're setting the image names in IB and trying to get that name after a touch event, in that case you could set the image name in the element's restoration ID and retrieve the name via the restorationIdentifier property of the touched element.

You can get the touched element like this:

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch: UITouch = touches.first {
        let location = touch.location(in: self.view)
        let touchedView = self.view.hitTest(location, with: event)

        print(touchedView.restorationIdentifier)
    }
}

Note that you have to set the image file name twice if you want to do it like this, and change the value twice when making changes. What you are trying smells of bad design, so if there's another way I'd go with that.

kevin
  • 442
  • 3
  • 13
0

if i got your question right, you dont wanna use @IBOutlet, but need to get the name of image clicked. So for this you can also give tag to UIImageView to identify them, and later can access any info.

first from storyboard, assign 1 or any int value to tag property and check User Interaction Enabled for ImageView.

Replace touchesEnded with the following lines-

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch: UITouch = touches.first {
            let location = touch.location(in: self.view)
            if let touchedView = self.view.hitTest(location, with: event) as? UIImageView {
                if touchedView.tag == 1 {
                    debugPrint(touchedView.image)
                }
            }
        }
    }

Hope it helps.

Maanu
  • 945
  • 1
  • 6
  • 10