iOS iOS - 6 months ago 24
Swift Question

Usage of #selector directive in Xcode 7.3

I have a protocol

protocol AnnotationTapDelegate: AnyObject {

/* Delegate to identify the tap on Annotation view */
func didTapAnnotation(sender: UITapGestureRecognizer)
}


and a class

class CustomAnnotationView: MKAnnotationView {
func setTapDelegate(delegate: AnnotationTapDelegate!) {
let tapGesture = UITapGestureRecognizer(target: delegate, action: #selector(AnnotationTapDelegate.didTapAnnotation(_:))) <== Error
self.addGestureRecognizer(tapGesture)
}
}


which gives me compile error saying "Argument of '#selector' refers to a method that is not exposed in Objective-C" and gives suggestion to "Add '@obj-c' to expose this to Objective-C". After adding '@obj-c' also, I get the same error and '@obj-c' is added again. Problem is not getting resolved.

I am working in Xcode 7.3.1.

Earlier I had

let tapGesture = UITapGestureRecognizer(target: delegate, action: "didTapAnnotation:")


which was working fine. After updating my Xcode to 7.3.1, I am facing this problem.

How would I set my protocol's function as selector?

Answer

You need to add @objc at the protocol level.

@objc
protocol AnnotationTapDelegate: AnyObject {

    /* Delegate to identify the tap on Annotation view */
    func didTapAnnotation(sender: UITapGestureRecognizer)
}