Добавление TapGestureRecognizer в UILabel в Swift

добавить UITapGestureRecognizer:tapGesture, Я хочу, чтобы при нажатии (касании) метки,klikPlay() будет запустить свои действия.

когда я запускаю код и нажимаю / касаюсь метки, он дает эту ошибку:

непризнанной селектор послал экземпляр.

речь идет о надписи Player(named: label) на UITapGestureRecognizer(named:tapGesture) и

что я делаю не так?

 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()
        })
        ] ))
}
}

3 ответов


похоже, вы объявили klikPlay как вложенная функция внутри didMoveToView:

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

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

он нужен вам как метод экземпляра вашего класса для распознавания жестов, чтобы найти его правильно:

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){
        // ...
    }
}

на основе ответ от Таймура Аджмала, специально для 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)")
}

довольно прямо вперед

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