shaibow
shaibow

Reputation: 105

assign a tap gesture recognizer to an image inside a scroll view in Swift

I'm trying to Create a scroll view of images and tappable like Appstore screen shots, When user touch on one image some action calls ! but here I can't find the problem that this doesn't work ! Notice that all of UI that i used is made by code!

func initScreenshots(){
    if screenShotsView.subviews.count > 0{
        screenShotsView.subviews.forEach({ $0.removeFromSuperview() })
    } 

    imageArray.append(UIImage.init(named: "1.jpeg")!)
    imageArray.append(UIImage.init(named: "2.jpeg")!)

    for image in imageArray {
        let index = imageArray.index(of: image)
        let imageView:UIImageView = {
            let iv = UIImageView()
            iv.image = image
            iv.translatesAutoresizingMaskIntoConstraints = false
            iv.contentMode = .scaleAspectFit
            return iv
        }()
        imageView.isUserInteractionEnabled = true
        imageView.addGestureRecognizer(tapGesture)
        screenShotsView.addSubview(imageView)
        imageView.topAnchor.constraint(equalTo: screenShotsView.topAnchor, constant: 10).isActive = true
        imageView.bottomAnchor.constraint(equalTo: screenShotsView.bottomAnchor, constant: 10).isActive = true
        imageView.heightAnchor.constraint(equalToConstant: 350).isActive = true
        imageView.widthAnchor.constraint(equalToConstant: 190).isActive = true
        if index == 0 {
            imageView.leftAnchor.constraint(equalTo: screenShotsView.leftAnchor, constant: 10).isActive = true                
        }else if( index == imageArray.count - 1 ){
            imageView.rightAnchor.constraint(equalTo: screenShotsView.rightAnchor, constant: 10).isActive = true
            imageView.leftAnchor.constraint(equalTo: ((screenShotsView.subviews[index! - 1]).rightAnchor), constant: 10).isActive = true
        }else{
            imageView.leftAnchor.constraint(equalTo: ((screenShotsView.subviews[index! - 1]).rightAnchor), constant: 10).isActive = true
        }
        imageView.isUserInteractionEnabled = true
        imageView.addGestureRecognizer(tapGesture)
    }

}

And you can see my gesture recognizer :

let tapGesture:UITapGestureRecognizer = {
    let gr = UITapGestureRecognizer(target: self, action: #selector(tapBlurButton(_:)))
    gr.numberOfTapsRequired = 1
    return gr
}()

My callback function is simple like this ! but it doesn't work :(

func tapBlurButton(_ sender: UITapGestureRecognizer) {
    print("Please Help!")
}

Upvotes: 2

Views: 845

Answers (1)

vacawama
vacawama

Reputation: 154711

Every imageView needs its own UITapGestureRecognizer. You can't create just one and use it multiple times.

Move the creation of the UITapGestureRecognizer into your loop and it will work.

Upvotes: 5

Related Questions