2016-07-11 117 views
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的实例,并且幸运的是,该手势识别器具有名为view的属性,该属性是gr所附加的视图。

... action: #selector(doubleTapTopComment(_:)) 

func doubleTapTopComment(gestureRecognizer: gr) { 
    // gr.view is the label, so you can say gr.view.text, for example 
} 
1

我相信UITapGestureRecognizer只能用于单个视图。也就是说,你可以有两个不同的UITapGestureRecognizer s调用相同的选择器,然后访问函数中的UITapGestureRecognizer。请看下面的代码:

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称这相同的功能:

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

如果您尝试添加UITapGestureRecognizer S的一到两个标签,则只有最后一个加入将实际调用功能。