Search code examples
swiftimageviewscrollviewuitapgesturerecognizer

Iterate through scrollView and find the clicked imageView


I have an horizontal scrollable ScrollView which has a lot of imageViews. I want to highlight the imageView a user has clicked on but I´m not sure how to do this. I have added a tap gesture to the image:

let tap = UITapGestureRecognizer(target: self, action: #selector(imgTapped(_:)))

But I´m not ure what to do in the imgTapped function from here... I have a unique tag for each imageView.

Any help would be appreciated.


Solution

  • If you have a collection of all your imageViews you could do something like this:

    func imgTapped(_ sender: UIGestureRecognizer) {
        // get the tag for the clicked imageView
        guard let tag = sender.view?.tag else { return }
    
        let imageView = ImageViews.filter { $0.tag == tag }.first
    }
    

    Otherwise you can iterate through your scrollViews subviews, checkout the comments and see what happens in the code:

    func imgTapped(_ sender: UIGestureRecognizer) {
        // get the tag for the clicked imageView
        guard let tag = sender.view?.tag else { return }
    
        // iterate through your scrollViews subviews
        // and check if it´s an imageView
        for case let imageView as UIImageView in self.imageScrollView.subviews {
            // check if the tag matches the clicked tag
            if imageView.tag == tag {
                // this is the tag the user has clicked on
                // highlight it here
            }
        }
    }