Adding TapGestureRecognizer to UILabel in Swift
Asked Answered
A

4

9

I add a UITapGestureRecognizer:tapGesture, I want that when I click(touch) the label, klikPlay() will run its actions.

when I run the code and click/touch the label, it gives this error:

unrecognized selector sent to instance.

It is about the label Player(named: label), the UITapGestureRecognizer(named:tapGesture) and the function klikPlay

What am I doing wrong?

 override func didMoveToView(view: SKView) {

let background = SKSpriteNode(imageNamed: "bgStart2")
background.position = CGPoint(x:0, y:0)
background.anchorPoint=CGPoint(x:0,y:1.0)
background.size = frame.size
addChild(background)


//label Play
var label: UILabel = UILabel()
label.frame = CGRectMake(frame.size.width/4, frame.size.height/9, frame.size.width, frame.size.height/6)
label.text = "Play"
label.font = UIFont(name: "Noteworthy-Bold", size:50)
label.textColor = UIColor.whiteColor()
label.textAlignment = NSTextAlignment.Center
label.center = CGPointMake(frame.size.width/2, 4 * frame.size.height/8 )
label.hidden = false

//label map
var label2: UILabel = UILabel()
label2.frame = CGRectMake(frame.size.width/4, frame.size.height/9, frame.size.width, frame.size.height/6)
label2.text = "Map"
label2.font = UIFont(name: "Noteworthy-Bold", size:50)
label2.textColor = UIColor.whiteColor()
label2.textAlignment = NSTextAlignment.Center
label2.center = CGPointMake(frame.size.width/2, 5 * frame.size.height/8 )
label2.hidden = false

//label sounds
var label3: UILabel = UILabel()
label3.frame = CGRectMake(frame.size.width/4, frame.size.height/9, frame.size.width, frame.size.height/6)
label3.text = "Sounds"
label3.font = UIFont(name: "Noteworthy-Bold", size:50)
label3.textColor = UIColor.whiteColor()
label3.textAlignment = NSTextAlignment.Center
label3.center = CGPointMake(frame.size.width/2, 6 * frame.size.height/8 )
label3.hidden = false


//label info
var label4: UILabel = UILabel()
label4.frame = CGRectMake(frame.size.width/4, frame.size.height/9, frame.size.width, frame.size.height/6)
label4.text = "Info"
label4.font = UIFont(name: "Noteworthy-Bold", size:50)
label4.textColor = UIColor.whiteColor()
label4.textAlignment = NSTextAlignment.Center
label4.center = CGPointMake(frame.size.width/2, 7 * frame.size.height/8 )
label4.hidden = false

self.view?.addSubview(label)
self.view?.addSubview(label2)
self.view?.addSubview(label3)
self.view?.addSubview(label4)

label.userInteractionEnabled = true
label2.userInteractionEnabled = true
label3.userInteractionEnabled = true
label4.userInteractionEnabled = true

 //the UITapGestureRecognizer
let tapGesture = UITapGestureRecognizer(target: self, action: "klikPlay:")
label.addGestureRecognizer(tapGesture)
view.addGestureRecognizer(tapGesture)



   //the functions I want to run 
func klikPlay(sender:UITapGestureRecognizer){
    var scene:GameScene!
    self.runAction(SKAction.sequence([SKAction.waitForDuration(0.0),
        SKAction.runBlock({
            // var transition:SKTransition = SKTransition.flipHorizontalWithDuration(0.5)
            var scene1:SKScene = GameScene(size: self.size)
            self.view?.presentScene(scene1)
            label.removeFromSuperview()
            label2.removeFromSuperview()
            label3.removeFromSuperview()
            label4.removeFromSuperview()
            background.removeFromParent()
        })
        ] ))
}
}
Anticipation answered 21/11, 2014 at 15:24 Comment(0)
T
6

It looks like you've declared klikPlay as a nested function inside didMoveToView:

override func didMoveToView(view: SKView) {
    // ...
    let tapGesture = UITapGestureRecognizer(target: self, action: "klikPlay:")

    func klikPlay(sender:UITapGestureRecognizer){
        // ...
    }
}

You need it as an instance method of your class for the gesture recognizer to find it properly:

class MyView {
    var label: UILabel!
    // ...

    override func didMoveToView(view: SKView) {
        label = UILabel()
        label.frame = CGRectMake(...)
        // ...
        let tapGesture = UITapGestureRecognizer(target: self, action: "klikPlay:")
    }

    func klikPlay(sender:UITapGestureRecognizer){
        // ...
    }
}
Teamster answered 21/11, 2014 at 16:20 Comment(4)
thank you but when i do that, the labels are not recognized in the klikplay function anymore because they are declared in the viewdidload function. how do i fix that? thank you!Anticipation
You'd need to declare them as instance variables of your class - see my update.Teamster
@Chris you saved my life, was wondering you gesture recognizer not working for an hourPiegari
@NateCook doesnt work for me for UILabel class.. can u check please? paste.ubuntu.com/26175422Gehlbach
T
19

Based on answer from Taimur Ajmal, Updated for Swift 2.X:

override func viewDidLoad() {
    super.viewDidLoad()

    ...

    labelDemo.userInteractionEnabled = true // Remember to do this
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(
        target: self, action: #selector(didTapLabelDemo))
    labelDemo.addGestureRecognizer(tap)
    tap.delegate = self // Remember to extend your class with UIGestureRecognizerDelegate

    ...
}

func didTapLabelDemo(sender: UITapGestureRecognizer)
{
    print("you tapped label \(sender)")
}
Telemeter answered 2/4, 2016 at 5:32 Comment(0)
B
13

Pretty straight forward

let tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "labelAction:")
mylabel.addGestureRecognizer(tap)
tap.delegate = self // Remember to extend your class with UIGestureRecognizerDelegate

 // Receive action
func labelAction(gr:UITapGestureRecognizer)
{
    let searchlbl:UILabel = (gr.view as! UILabel) // Type cast it with the class for which you have added gesture
    print(searchlbl.text)    
}
Beccafico answered 29/11, 2015 at 12:14 Comment(0)
T
6

It looks like you've declared klikPlay as a nested function inside didMoveToView:

override func didMoveToView(view: SKView) {
    // ...
    let tapGesture = UITapGestureRecognizer(target: self, action: "klikPlay:")

    func klikPlay(sender:UITapGestureRecognizer){
        // ...
    }
}

You need it as an instance method of your class for the gesture recognizer to find it properly:

class MyView {
    var label: UILabel!
    // ...

    override func didMoveToView(view: SKView) {
        label = UILabel()
        label.frame = CGRectMake(...)
        // ...
        let tapGesture = UITapGestureRecognizer(target: self, action: "klikPlay:")
    }

    func klikPlay(sender:UITapGestureRecognizer){
        // ...
    }
}
Teamster answered 21/11, 2014 at 16:20 Comment(4)
thank you but when i do that, the labels are not recognized in the klikplay function anymore because they are declared in the viewdidload function. how do i fix that? thank you!Anticipation
You'd need to declare them as instance variables of your class - see my update.Teamster
@Chris you saved my life, was wondering you gesture recognizer not working for an hourPiegari
@NateCook doesnt work for me for UILabel class.. can u check please? paste.ubuntu.com/26175422Gehlbach
C
-3
  @IBOutlet weak var mylabel: UILabel!
var tap = UITapGestureRecognizer()
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    tap = UITapGestureRecognizer(target: self, action:#selector(ViewController.handleTap(_sender:)))
           mylabel.isUserInteractionEnabled = true
    tap.numberOfTapsRequired = 1
    mylabel.addGestureRecognizer(tap)
   self.view.addSubview(mylabel)
    
}
@objc func handleTap(_sender:UITapGestureRecognizer){
    mylabel.backgroundColor = .red
    mylabel.backgroundColor = .black
}

}

Cowie answered 22/11, 2023 at 13:3 Comment(1)
1. Please do not post duplicate answers. An answer should add value not found in other answers. 2. Please do not post code-only answers. A good answer explains the issue in the question and it explains how the answer solves the issue. 3. Please take the time to properly format the code in the answer. This includes proper indenting and spacing. Take pride in what you post.Kendrick

© 2022 - 2024 — McMap. All rights reserved.