Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
519 views
in Technique[技术] by (71.8m points)

ios - Pass extra argument for UItapgestureRecognizer with selector

I have two labels, Label1 and Label2. I want to make a single function that prints out which label is tapped by creating UITTapRecognizer for both labels calling the same function with selector that passes an argument. Below is the long way of doing it which is messy but works. If I know how to pass an argument (Int) into the selector, it would be alot cleaner.

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

Is there a way to modify the selector method such that I can do something like

func doubleTapTopComment(label:Int) {
    if label == 1 {
        print("label (label) double tapped")
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Short answer: no

The selector is called by the UITapGestureRecognizer, and you have no influence on what parameters it passes.

However, what you can do is query the recognizer's view property to get the same information.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...