iOS无法识别的选择器发送到Swift中的实例 [英] iOS unrecognized selector sent to instance in Swift
问题描述
我在尝试让UIButton在用户按下时工作时遇到问题。我一直收到错误说:发送到实例的无法识别的选择器
I am having problems with trying to get a UIButton to work when the user presses it. I keep getting an error saying: unrecognised selector sent to instance
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"
}
对于Swift方法,例如 func buttonClick(发件人:UIButton)
传递给<$ c $的正确字符串是什么c> addTarget 选择器的方法?是buttonClick,buttonClick:,buttonClickSender:还是其他什么?
For a Swift method such as func buttonClick(Sender: UIButton)
what is the correct string to pass to addTarget
method for the selector? Is it "buttonClick", "buttonClick:", "buttonClickSender:" or something else?
推荐答案
您使用的是无效的动作的方法签名。你提供 buttonClick
,但该方法有一个参数,所以签名应该是 buttonClick:
You're using an invalid method signature for the action. You're supplying buttonClick
, but the method has an argument, so the signature should be buttonClick:
button.addTarget(self, action: "buttonClick:", forControlEvents: UIControlEvents.TouchUpInside)
有关如何设置选择器格式的详细信息,请参阅下面链接的帖子中的接受答案。这篇文章中使用的代码可能是Objective-C,但它的所有课程也可以在这里应用。
For more information about how to format your selectors, you can refer to the accepted answer in the post linked below. The code used in this post may be Objective-C, but all its lessons can be applied here as well.
并且作为旁注,如果您使用 Selector(buttonClicked:)
作为操作,此代码也将有效,但您不必因为字符串文字可以隐式地转换为选择器类型。
And as a side note, this code would also be valid if you used Selector("buttonClicked:")
as the action, but you don't have to because string literals can be implicitly cast to the Selector type.
引自将Swift与Cocoa和Objective-C一起使用
Objective-C选择器是一种引用
Objective-C方法名称的类型。在Swift中,Objective-C选择器由
Selector结构表示。您可以使用字符串
literal构造一个选择器,例如let mySelector:Selector =tappedButton:。因为
字符串文字可以自动转换为选择器,所以
可以将字符串文字传递给任何接受选择器的方法。
An Objective-C selector is a type that refers to the name of an Objective-C method. In Swift, Objective-C selectors are represented by the Selector structure. You can construct a selector with a string literal, such as let mySelector: Selector = "tappedButton:". Because string literals can be automatically converted to selectors, you can pass a string literal to any method that accepts a selector.
这篇关于iOS无法识别的选择器发送到Swift中的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!