UI元素setAction和setTarget不起作用

时间:2011-06-29 06:16:13

标签: xcode uibutton action target

我找到了一些问题的答案,但它仍然无效。我在IB中设置了一个按钮,我想通过代码设置动作和目标(仅用于学习)。我在MainViewController中有一个函数:

- (IBAction) onSpecialCase:(id)sender {
    NSLog(@"It's working");
}

在viewDidLoad函数中我这样做:

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view from its nib.
[myButton setTarget:self];
[myButton setAction:@selector(onSpecialCase:)];
}

Xcode已标记这些行告诉我:“UIButton可能无法响应'setTarget'”。无论如何,当运行应用程序时它终止说:

-[UIRoundedRectButton setTarget:]: unrecognized selector sent to instance 0x4b47e30
2011-06-29 08:12:22.465 FirstTry[3765:207] *** Terminating app due to uncaught exception     'NSInvalidArgumentException', reason: '-[UIRoundedRectButton setTarget:]: unrecognized selector sent to instance 0x4b47e30'

这就是我对XCode警告的期望,但为什么呢?我在网上找到的每个例子都和我的一样。通过IB将actionMethode添加到按钮的工作方式与预期的一样。我做错了什么?

2 个答案:

答案 0 :(得分:9)

首先检查您是否已将按钮声明为插座,然后您应检查是否将插座连接到按钮或使用我通常所做的是在代码中添加新按钮

UIButton *Button=[UIButton buttonWithType:UIButtonTypeCustom] ;
Button.frame=CGRectMake(0,0,30,30); // place your button
[Button addTarget:self action:@selector(processButtonCLick) forControlEvents:UIControlEventTouchUpInside];
[Button setImage:[UIImage imageNamed:@"imageoricon.png"] forState:UIControlStateNormal];
[self.view addSubview:Button];

答案 1 :(得分:2)

它可能对你有帮助。

UIButton *sendButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [sendButton setTitle:@"Send" forState:UIControlStateNormal];

    [sendButton.titleLabel setFont:[UIFont boldSystemFontOfSize:12]];
    sendButton.frame = CGRectMake(0, 3, 67, 37);
    [sendButton addTarget:self action:@selector(sendButtonClicked) forControlEvents:UIControlEventTouchUpInside];