umair151 umair151 - 7 months ago 36
Swift Question

Setting static method as action of UITapGestureRecognizer in 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:]

Answer

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.

Comments