2016-07-11 8 views
2

私は2つのラベルLabel1とLabel2を持っています。引数を渡すセレクタで同じ関数を呼び出す両方のラベルのUITTapRecognizerを作成することによって、どのラベルがタップされるかを出力する単一の関数を作成したいと思います。以下は、これを行うための長い道のりが乱雑ですが、機能します。私がセレクタに引数(Int)を渡す方法を知っていれば、それはもっときれいになります。セレクタ付きのUItapgestureRecognizerに余分な引数を渡す

let topCommentLbl1Tap = UITapGestureRecognizer(target: self, action: #selector(DiscoverCell().doubleTapTopComment1)) 
    topCommentLbl1Tap.numberOfTapsRequired = 2 
    topCommentLbl1.userInteractionEnabled = true 
    topCommentLbl1.addGestureRecognizer(topCommentLbl1Tap) 

let topCommentLbl2Tap = UITapGestureRecognizer(target: self, action: #selector(DiscoverCell().doubleTapTopComment2)) 
     topCommentLbl2Tap.numberOfTapsRequired = 2 
     topCommentLbl2.userInteractionEnabled = true 
     topCommentLbl2.addGestureRecognizer(topCommentLbl2Tap) 

func doubleTapTopComment1() { 
    print("Double Tapped Top Comment 1") 
} 
func doubleTapTopComment2() { 
    print("Double Tapped Top Comment 2") 
} 

私は何かのよう

func doubleTapTopComment(label:Int) { 
    if label == 1 { 
     print("label \(label) double tapped") 
} 

答えて

2

短い答えを行うことができるように、セレクタ方式を変更する方法はあります:セレクタがUITapGestureRecognizerによって呼び出され、あなたがいない持っている

ませんそれが通過するパラメータに及ぼす影響。

ただし、認識プログラムのviewプロパティを照会して同じ情報を取得することができます。

func doubleTapComment(recognizer: UIGestureRecognizer) { 
    if recognizer.view == label1 { 
     ... 
    } 
    else if recognizer.view == label2 { 
     ... 
    } 
} 
2

ジェスチャ認識器の両方に、単一のパラメータを取る同じセレクタを提供します。そのアクションメソッドはUIGestureRecognizerのインスタンスに渡され、うれしく、ジェスチャ認識プログラムにはgrが添付されたビューであるviewというプロパティがあります。

1

私はUITapGestureRecognizerを1つのビューにしか使用できないと考えています。つまり、2つの異なるUITapGestureRecognizerが同じセレクタを呼び出して、その関数内のUITapGestureRecognizerにアクセスすることができます。あなたは最後のものだけが実際に呼び出されます追加、両方のラベルにUITapGestureRecognizer秒の1を追加しようと

func whichLabelWasTapped(sender : UITapGestureRecognizer) { 
    //print the tag of the clicked view 
    print (sender.view!.tag) 
} 

import UIKit 

class ViewController: UIViewController { 

    override func viewDidLoad() { 

     super.viewDidLoad() 

     let label1 = UILabel() 
     label1.backgroundColor = UIColor.blueColor() 
     label1.frame = CGRectMake(20, 20, 100, 100) 
     label1.tag = 1 
     label1.userInteractionEnabled = true 
     self.view.addSubview(label1) 

     let label2 = UILabel() 
     label2.backgroundColor = UIColor.orangeColor() 
     label2.frame = CGRectMake(200, 20, 100, 100) 
     label2.tag = 2 
     label2.userInteractionEnabled = true 
     self.view.addSubview(label2) 

     let labelOneTap = UITapGestureRecognizer(target: self, action: #selector(ViewController.whichLabelWasTapped(_:))) 
     let labelTwoTap = UITapGestureRecognizer(target: self, action: #selector(ViewController.whichLabelWasTapped(_:))) 

     label1.addGestureRecognizer(labelOneTap) 
     label2.addGestureRecognizer(labelTwoTap) 

} 

どちらUITapGestureRecognizer sが同じ関数を呼び出す:次のコードを参照してください。関数。

関連する問題