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:

enter image description here

but when used, gave compile warning saying:

enter image description here

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

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -