Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting static method as action of UITapGestureRecognizer in Swift

Tags:

ios

swift

I am creating a UIView programmatically in static method and want to add UITapGestureRecognizer which will call another static method in my Helper class.

Helper.swift :

static func showLoadingPopUp(frame: CGRect) -> UIView {
  let transView = UIView.init(frame: frame!)       
  let tapGesture = UITapGestureRecognizer(target: self, action: "transViewTapped:")
  transView.addGestureRecognizer(tapGesture)
  return transView
}

static func transViewTapped(gesture: UITapGestureRecognizer) {
  print("Oh Tapped!!!")
}

But it ends up with the following message probably because of the static nature of my method. Also Helper.swift is simple swift class (not UIView or UIViewController)

Error:

Unrecognized selector +[JaClassified.Helper transViewTapped:]

like image 973
umair151 Avatar asked Oct 18 '22 11:10

umair151


1 Answers

If your class is not a descendant of NSObject, you may need to bridge the static func to Objective-C (since old style Objective-C selector works on NSObjects).

So, in your case, you could either declare you Helper class as

class Helper: NSObject {
    ...
}

or, you can bridge your transViewTapped: to Objective-C by prefix it with an @objc

@objc static func transViewTapped(gesture: UITapGestureRecognizer) {
    ...
}

Hope it helps.

like image 133
Cheng-Yu Hsu Avatar answered Nov 03 '22 22:11

Cheng-Yu Hsu