开发者

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 t开发者_开发百科rying to generalize and my attempts have thus far been unfruitful.

Thanks


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];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜