“#selector”的参数不涉及“@objc”方法,属性或初始值设定项

我在Swift 3中声明了一个用Objective-C编写的UIButton子类。

当我尝试添加目标时,会失败,并显示错误代码:

 class ActionButton: JTImageButton { func action() { } func configure()) { // ... self.addTarget(self, action: #selector(self.action()), for: .touchUpInside) // error: // Argument of '#selector' does not refer to an '@objc' method, property, or initializer } } 

你所要做的就是将func标记为@objc ,不需要self引用或括号

 class ActionButton: JTImageButton { @objc func btnAction() { } func configure() { // ... self.addTarget(self, action: #selector(btnAction), for: .touchUpInside) // error: // Argument of '#selector' does not refer to an '@objc' method, property, or initializer } } 

你甚至可以把它private如果你想要的

问题是在#selector(self.action())self.action()是一个方法调用 。 你不想调用这个方法; 你想命名该方法。 说#selector(action)而不是:丢失括号,再加上没有必要的self

func action()不仅仅是一个函数名称和动作的糟糕select,它不能构build。 (虽然你可以用它作为input函数的参数,但是为了清晰起见,当把target / action传递给一个init()来设置这些东西的时候。 为了清楚起见,我用MyAction()replace了这个参数。


尝试这个:

 self.addTarget(self, action: #selector(MyAction), for: .touchUpInside) 

说,更好的devise是将MyAction()函数移动到button超级视图,因为这使得事情与基本的MVCdevise更加一致:

上海华:

 let myButton = ActionButton() // include other button setup here myButton.addTarget(self, action: #selector(MyAction), for: .touchUpInside func action(_ sender: ActionButton) { // code against button tap here } 

替代编码,保持视图控制器中的“action()”方法,但移动“addTarget”到button中:

 self.addTarget(superview?, action(superview?.MyAction), for: .touchUpInside) 

为什么我要求你考虑把“MyAction()”方法移到superview? 双重:

  • 它不仅控制button,还控制视图中的所有其他子视图,并且它们通常通过视图控制器相互交互。
  • 它使得button在其他情况下更加可重用。

而不是说self.action() ,使用self.action() ActionButton.action()

在前面添加@objc关键字是完美的方法,但我仍然有这个错误。 最后,我find了如下解决scheme 在这里输入图像说明

方法背后有一对多余的括号,如上图所示。 我应该做的是删除它,它运作良好。

如果你不介意增加一个额外的function,你可以嵌套function。

 self.addTarget(self, action: myAction, for: UIControlledEvent) myAction(){ @obj.methodYouWantToCall(//parameters//) }