2017-04-20 16 views
1

画像のスクロールビューを作成しようとしています.Appstoreスクリーンショットのようにタップ可能です。 ユーザーが1つの画像をタッチすると、しかし、ここで私はこれが動作しないという問題を見つけることができません! 私が使用したUIはすべてコードで作成されていることに注意してください。Swiftのスクロールビュー内の画像にタップジェスチャ認識機能を割り当てます。

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!") 
} 
+0

ボタンを使用して、ボタンの背景画像を設定してみましたか? –

+0

@OrenEdrichいいえ、私のビューにはこのジェスチャ認識機能を追加しましたがまだ動作していないボタンがあります:( – shaibow

+1

ボタンにジェスチャ認識機能を追加する必要はありません。 .swiftファイルに接続します。またはif(あなたのボタン)を作成します.isSelected = true {あなたのコード} –

答えて

2

すべてimageViewは自身のUITapGestureRecognizer。あなたが複数回1つだけ作成し、それを使用することはできませんその必要があります。

はあなたのループとそれに UITapGestureRecognizerの作成を移動します

関連する問題