Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS unrecognized selector sent to instance in Swift

Tags:

ios

swift

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"
}

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?

like image 993
Stephen Fox Avatar asked Jun 11 '14 00:06

Stephen Fox


People also ask

What is #selector in Swift?

Use Selectors to Arrange Calls to Objective-C Methods In Objective-C, a 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, and you create them using the #selector expression.

What is an unrecognized selector?

Once you run this line of code you will instantly get an error message in the console area, which look s like this (unrecognized selector sent to instance). Since the selector is another name for the method, the error is basically saying that it doesn't recognize the function that you're trying to call on this object.


1 Answers

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)

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.

Creating a selector from a method name with parameters

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.

Quoting from Using Swift with Cocoa and Objective-C

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.

like image 62
Mick MacCallum Avatar answered Sep 22 '22 06:09

Mick MacCallum