参数化的UIButton动作选择器用于另一个类中的方法?

Old*_*her 4 iphone cocoa-touch objective-c uibutton

这在很大程度上是一个语法问题.如何设置UIButton操作选择器来调用不同类的方法?我已经完成了类的#import,我需要使用按钮调用它的方法,我对按钮代码的外观有以下部分理解:

    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];
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下错误:

预期':'在'''之前

@selector中缺少方法名称

我在参考库中看到的示例代码调用了本地方法,所以我试图概括并且我的尝试迄今为止都没有用.

谢谢

小智 10

选择器是方法名称的表示,无论哪个类或类别实现它.

假设您有一个AnotherClass实现该方法的类- (void)doSomething:(id)sender.相应的选择器doSomething:在代码中表示为@selector(doSomething:).如果您希望按钮操作调用该方法,则需要具有 - 的实例AnotherClass- 而该实例是操作目标,而不是self.因此,您的代码应具有:

#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];
Run Code Online (Sandbox Code Playgroud)

  • @OldMcStopher有关Cocoa Touch接受的预定义操作签名列表,请参阅此参考:http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/CocoaFundamentals/CommunicatingWithObjects/CommunicateWithObjects.html%23//apple_ref/DOC/UID/TP40002974-CH7-SW44 (2认同)