Jimmery
Jimmery

Reputation: 10119

Using Selectors as variables with addTarget

I am having problems with Selectors in Swift. I have the following lines of code:

let actionTarget="onPress:"
button.addTarget(self, action: Selector(actionTarget), forControlEvents: .TouchUpInside)

But this generates the error:

! Could not find member 'TouchUpInside'

However this error disappears if I try:

button.addTarget(self, action "onPress:", forControlEvents: .TouchUpInside)

So I am assuming its not the .TouchUpInside that is causing me problems, but its the lack of a string literal that is causing me problems.

I have also tried:

let actionTarget="onPress:" as Selector
button.addTarget(self, action: actionTarget, forControlEvents: .TouchUpInside)

But that didnt work either.

How can I supply the action with a Selector that is not a string literal, but instead stored in a variable?

Upvotes: 0

Views: 790

Answers (1)

DPlusV
DPlusV

Reputation: 14326

button.addTarget(self, action: "onPress:", forControlEvents: .TouchUpInside)

This one's correct -- you don't need to do anything special like Selector() to use a selector, simply using a string will do.

If your selector is stored in a variable, then use this:

let selector = "onPress:"
button.addTarget(self, action: Selector(selector), forControlEvents: .TouchUpInside)

The reason as isn't correct here is because it's used to cast from a superclass to a subclass. For example, let p:UIView = UIButton(...) and p as UIButton would work since p is in fact a UIButton instance. In this case, using Selector( ... ) calls the appropriate Selector constructor and instantiates a new Selector from your String.

Upvotes: 2

Related Questions