将快速手势识别器分配给Swift中滚动视图内的图像

时间:2017-04-20 13:52:16

标签: swift uiscrollview uigesturerecognizer

我正在尝试创建图像的滚动视图,并像Appstore屏幕截图一样进行点播, 当用户触摸一个图像时,会有一些动作调用!但在这里我找不到这个不起作用的问题! 请注意,我使用的所有UI都是由代码生成的!

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)
    }

}

你可以看到我的手势识别器:

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

我的回调功能很简单!但它不起作用:(

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

1 个答案:

答案 0 :(得分:2)

每个imageView都需要自己的UITapGestureRecognizer。您不能只创建一个并多次使用它。

UITapGestureRecognizer的创建移动到循环中,它将起作用。