在分页ScrollView中将TapGesture添加到ImageView

时间:2019-04-27 21:35:41

标签: ios swift

我有一个分页UIScrollView,每个页面只有一个UIImageView和一个View。我想添加对视图上显示的图像的描述,我希望能够通过点击UIImageView来显示/隐藏视图。

我尝试了几种添加GestureRecognizer的方法,但是似乎不起作用。下面的代码是创建我的页面的地方。幻灯片1和幻灯片2显示了2种不同的方式,我尝试添加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)

我认为我对这些页面的创建方式有误解,希望有人能帮助我。

谢谢!

1 个答案:

答案 0 :(得分:1)

  1. tapGesture中将createSlides创建为局部变量。
  2. 每个视图都需要自己的手势识别器。您可以共享选择器,但不能共享手势。

更新的代码:

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)