Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

swift - Swift3 iOS - How to make UITapGestureRecognizer trigger function

I am trying to add a UITapGesture to a UIButton so it will trigger a function when tapped. I am using Swift 3 and is getting some error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[SwiftRunner.ViewController tapBlurButton]: unrecognized selector sent to instance 0x149e07610'

This is roughly what I have:

// Swift 3
import UIKit
class ViewController {

   @IBOutlet weak var qsBlurButton: UIButton!       

   override func viewDidLoad() {
      super.viewDidLoad()

      let tapGesture = UITapGestureRecognizer(target: self, action: Selector(("tapBlurButton")))
      qsBlurButton.addGestureRecognizer(tapGesture)
   }

   func tapBlurButton(sender: UITapGestureRecognizer) {
      print("Please Help!")
   }
}
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

From your code you are using swift 3.0 so change your selector syntax like this

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapBlurButton(_:)))

and Your function like this

func tapBlurButton(_ sender: UITapGestureRecognizer) {
    print("Please Help!")
}

Edit:

Not idea that you are using button with tap gesture, instead of that use inbuilt method addTarget for button no need to create tap gesture for it like this

qsBlurButton.addTarget(self, action: #selector(self.tapBlurButton(_:)), forControlEvents: .TouchUpInside)

func tapBlurButton(_ sender: UIButton) {
    print("Please Help!")
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...