gpt4 book ai didi

swift - 添加 UIButton 目标时为 "classname has no member functionname"

转载 作者:行者123 更新时间:2023-11-30 12:35:53 25 4
gpt4 key购买 nike

这里是 Swift 和 iOS 开发的 super 新手。

我正在关注this tutorial关于在单 View iOS 应用程序中实现自定义控件。这是一个 Swift 2 教程,但到目前为止,我已经可以将所有内容转换为 3(我使用 XCode 8 Beta)。

我有一个自定义类,RatingControl,连接到 Storyboard中的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 👍")
}

但是当我编译时,它会提示:

type "RatingControl" has no member "ratingButtonTapped"

我已经 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)

关于swift - 添加 UIButton 目标时为 "classname has no member functionname",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42878361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com