ios - Swift 2.2 #selector for delegate/protocol compile error -
here code:
protocol customcontroldelegate: anyobject { func buttontapped(sender: anyobject) } class customcontrol: uiview { var delegate: customcontroldelegate? { didset { abutton.addtarget(delegate, action: "buttontapped:"), forcontrolevents: uicontrolevents.touchupinside) } } as of swift 2.2, compile error asking use #selector. can't figure out how correctly use #selector in case.
the compiler gave suggestion:
but when used, gave compile warning saying:
i tried , did not compile error, however, doubt it's right solution. don't want add @objc protocol:
@objc protocol customcontroldelegate: anyobject { func buttontapped(sender: anyobject) } class customcontrol: uiview { var delegate: customcontroldelegate? { didset { abutton.addtarget(delegate, action: #selector(customcontroldelegate.buttontapped(_:)), forcontrolevents: uicontrolevents.touchupinside) } }
i don't see reason avoid @objc here. method must @objc in order objective-c runtime invoke it. can't put @objc method declaration, way convey intent make protocol @objc.
@objc protocol customcontroldelegate { func buttontapped(sender: anyobject) } although protocol @objc, implementing class not need @objc — making method @objc can make compiler happy.
class mycontroldelegate: customcontroldelegate { // ^ no `@objc`, not deriving nsobject @objc func buttontapped(sender: anyobject) { // ^ making method `@objc` enough. } } then use #selector(customcontroldelegate.buttontapped) without errors or warnings.


Comments
Post a Comment