简体   繁体   中英

Adding TapGesture to ImageViews in paging ScrollView

I have a paging UIScrollView , each page just has an UIImageView and a View. I would like to add a description of the Image shown on the View, and I want to be able to show/hide the View by tapping the UIImageView .

I have tried a few ways of adding the GestureRecognizer , but it does not seem to work. The Code below is where my Pages get created. With Slide1 and Slide 2 showing 2 different ways I tried to add the GestureRecognizer .

   let tapGesture = UITapGestureRecognizer(target: self, action: #selector(showOrHide))

@objc func showOrHide(){
    print("tapped")

    for slide in slides{

        slide.labelView.isHidden = true
    }
}


func createSlides() -> [Slide] {
    print("creating Slides")
    let slide1:Slide = Bundle.main.loadNibNamed("Slide", owner: self, options: nil)?.first as! Slide
    slide1.imageView.image = UIImage(named: "img1.jpg")
    slide1.imageView.isUserInteractionEnabled = true
    slide1.tapGestureRecogizer = UITapGestureRecognizer(target: self, action: #selector(showOrHide))

    let slide2:Slide = Bundle.main.loadNibNamed("Slide", owner: self, options: nil)?.first as! Slide
    slide2.imageView.image = UIImage(named: "img2.jpg")
    slide2.imageView.isUserInteractionEnabled = true
    slide2.imageView.addGestureRecognizer(tapGesture)

I assume I am misunderstanding something about how these Pages get created, I hope someone can help me.

Thank you!

  1. Create tapGesture as a local variable inside createSlides .
  2. Each view needs its own gesture recognizer. You can share the selector but not the gesture.

Updated code:

func createSlides() -> [Slide] {
    print("creating Slides")

    let slide1 = Bundle.main.loadNibNamed("Slide", owner: self, options: nil)?.first as! Slide
    slide1.imageView.image = UIImage(named: "img1.jpg")
    slide1.imageView.isUserInteractionEnabled = true

    var tapGesture = UITapGestureRecognizer(target: self, action: #selector(showOrHide))
    slide1.imageView.addGestureRecognizer(tapGesture)

    let slide2 = Bundle.main.loadNibNamed("Slide", owner: self, options: nil)?.first as! Slide
    slide2.imageView.image = UIImage(named: "img2.jpg")
    slide2.imageView.isUserInteractionEnabled = true

    tapGesture = UITapGestureRecognizer(target: self, action: #selector(showOrHide))
    slide2.imageView.addGestureRecognizer(tapGesture)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM