1
votes

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.

2
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
@stephen Its a mix of static images and dynamic images within a stackview.Daniel Åsberg
Check this answer: stackoverflow.com/a/5192999/1718685 you should be able to determine the view below the touch.Stephen

2 Answers

0
votes

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.

0
votes

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.