Swift: Long Press Gesture Recognizer - Detect taps and Long Press

前端 未结 3 1284
情话喂你
情话喂你 2020-12-05 00:11

I want to wire an action such that if the gesture is a tap, it does animates an object in a particular way but if the press duration was more than .5 secs it does something

3条回答
  •  星月不相逢
    2020-12-05 00:58

    Define two IBActions and set one Gesture Recognizer to each of them. This way you can perform two different actions for each gesture.

    You can set each Gesture Recognizer to different IBActions in the interface builder.

    @IBAction func tapped(sender: UITapGestureRecognizer)
    {
        println("tapped")
        //Your animation code.
    }
    
    @IBAction func longPressed(sender: UILongPressGestureRecognizer)
    {
        println("longpressed")
        //Different code
    }
    

    Through code without interface builder

    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "tapped:")
        self.view.addGestureRecognizer(tapGestureRecognizer)
        
    let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "longPressed:")
        self.view.addGestureRecognizer(longPressRecognizer)
    
    func tapped(sender: UITapGestureRecognizer)
    {
        println("tapped")
    }
    
    func longPressed(sender: UILongPressGestureRecognizer)
    {
        println("longpressed")
    }
    

    Swift 5

    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapped))
    self.view.addGestureRecognizer(tapGestureRecognizer)
        
    let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressed))
    self.view.addGestureRecognizer(longPressRecognizer)
        
    @objc func tapped(sender: UITapGestureRecognizer){
        print("tapped")
    }
    
    @objc func longPressed(sender: UILongPressGestureRecognizer) {
        print("longpressed")
    }
    

提交回复
热议问题