添加UIButton目标时,类名称没有成员函数 [英] "classname has no member functionname" when adding UIButton target

查看:38
本文介绍了添加UIButton目标时,类名称没有成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是SWIFT和iOS开发方面的超级新手。

我正在关注this tutorial关于在单视图iOS应用程序中实现自定义控件的问题。这是一个SWIFT 2教程,但到目前为止,我可以将所有内容都转置到3(我使用的是XCode8测试版)。

我有一个自定义类RatingControl,它连接到情节提要中的View

在类的构造函数中,我创建了一个按钮:

let button = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
button.backgroundColor = UIColor.red()

然后,我尝试为该按钮分配一个操作。教程说我应该这样做:

button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)), 
for: .touchDown)       

,然后在同一个RatingControl类中创建方法:

func ratingButtonTapped(button: UIButton) {
  print("Button pressed 👍")
}

但当我编译时,它会抱怨:

类型"RatingControl"没有成员"ratingButtonTated"

我已经100%确定该函数在那里,在类中,并且命名正确。Full source

我有什么明显的遗漏吗?

我尝试的内容:

  • 根据this answer@objc添加到类定义中(但对于仅限SWIFT的对象,这似乎很奇怪,不是吗?)

  • 显式ratingButtonTapped()public(但看起来不需要)

  • 摆弄字符串而不是选择器,button.addTarget(self, action: "RatingControl.ratingButtonTapped", for: .touchDown)等等,但这只会在以后使其崩溃。

推荐答案

在SWIFT 3中,func ratingButtonTapped(button: UIButton)的方法引用变为ratingButtonTapped(button:)

因此,使用#selector(RatingControl.ratingButtonTapped(button:))也可以。

如果您想保留#selector(RatingControl.ratingButtonTapped(_:)),则需要将ratingButtonTapped方法声明为:

func ratingButtonTapped(_ button: UIButton) { //<- `_`
    print("Button pressed 👍")
}

如果类中只有一个ratingButtonTapped方法,则可以将选择器称为#selector(RatingControl.ratingButtonTapped)或简单地(从RatingControl类内部)#selector(ratingButtonTapped)

这篇关于添加UIButton目标时,类名称没有成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆