iOS无法识别的选择器发送到Swift中的实例

Ste*_*Fox 6 ios swift

当用户按下UIButton时,我遇到了问题.我一直收到错误说:无法识别的选择器发送到实例

override func viewDidLoad() {
    super.viewDidLoad()

    button.addTarget(self, action: "buttonClick", forControlEvents: UIControlEvents.TouchUpInside)
    button.setTitle("Print", forState: UIControlState.Normal)
    button.font = UIFont(name: "Avenir Next", size: 14)
    button.backgroundColor = UIColor.lightGrayColor()
    self.view.addSubview(button)
}

func buttonClick(Sender: UIButton!)
{
    myLabelInfo.text = "Hello"
}
Run Code Online (Sandbox Code Playgroud)

对于Swift方法,例如func buttonClick(Sender: UIButton)传递给addTarget选择器方法的正确字符串是什么?是"buttonClick","buttonClick:","buttonClickSender:"还是其他什么?

Mic*_*lum 22

您正在为操作使用无效的方法签名.您正在提供buttonClick,但该方法有一个参数,因此签名应该是buttonClick:

button.addTarget(self, action: "buttonClick:", forControlEvents: UIControlEvents.TouchUpInside)
Run Code Online (Sandbox Code Playgroud)

有关如何设置选择器格式的详细信息,请参阅下面链接的帖子中的接受答案.这篇文章中使用的代码可能是Objective-C,但它的所有课程也可以在这里应用.

使用参数从方法名称创建选择器

作为旁注,如果您将此代码用作Selector("buttonClicked:")操作,则此代码也是有效的,但您不必这样做,因为字符串文字可以隐式转换为Selector类型.

引用使用Swift与Cocoa和Objective-C

Objective-C选择器是一种引用Objective-C方法名称的类型.在Swift中,Objective-C选择器由Selector结构表示.您可以使用字符串文字构造一个选择器,例如让mySelector:Selector ="tappedButton:".因为字符串文字可以自动转换为选择器,所以您可以将字符串文字传递给任何接受选择器的方法.


Tom*_*cik 11

斯威夫特<2.2

在Swift <2.2中,选择器方法不能private(无法识别的选择器错误).

首选(由Apple)表示法是字符串"methodWithParam:"表示法.

故障排除:如果你有NSTimer选择器的麻烦,也许你的类应该是一个子类NSObject.

斯威夫特> = 2.2

使用#selector符号.在这里阅读更多内容:https://github.com/apple/swift-evolution/blob/master/proposals/0022-objc-selectors.md

对于私有方法,您可以使用@objc方法修饰符,如下所示:@objc private func timerTick(timer: NSTimer).

不再需要子类NSObject了!