Old McStopher
Old McStopher

Reputation: 6349

Parameterized UIButton action selector for method in another class?

This is largely a syntactical question. How does one set the UIButton action selector to call a method of a different class? I've done a #import of the class whose methods I need to call with the button and I have the following partial understanding of what the button code should look like:

    UIButton *btnSplash = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnSplash.frame = CGRectMake(250, 270, 180, 30);
    [btnSplash setTitle:@"Menu" forState:UIControlStateNormal];
    [btnSplash addTarget:self action:@selector([CLASS METHOD:PARAMETER]) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:btnSplash];

However, I get the following errors:

expected ':' before '[' token

method name missing in @selector

The sample code I've seen in the reference library calls local methods, so I'm trying to generalize and my attempts have thus far been unfruitful.

Thanks

Upvotes: 4

Views: 5340

Answers (1)

user557219
user557219

Reputation:

A selector is a representation of a method name regardless of which classes or categories implement it.

Say you have a class called AnotherClass which implements the method - (void)doSomething:(id)sender. The corresponding selector is doSomething:, represented in code as @selector(doSomething:). If you want the button action to invoke that method, you need to have an instance of AnotherClass — and it is this instance that is the action target, instead of self. Hence your code should have:

#import "AnotherClass.h"

AnotherClass *instanceOfAnotherClass;
// assign an instance to instanceOfAnotherClass

UIButton *btnSplash = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btnSplash.frame = CGRectMake(250, 270, 180, 30);
[btnSplash setTitle:@"Menu" forState:UIControlStateNormal];

[btnSplash addTarget:instanceOfAnotherClass
              action:@selector(doSomething:)
    forControlEvents:UIControlEventTouchUpInside];

[self addSubview:btnSplash];

Upvotes: 10

Related Questions