问题描述
这里是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)
。