xcode UI 元素 setAction 和 setTarget 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6516449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 21:22:26  来源:igfitidea点击:

UI Element setAction and setTarget not working

xcodeuibuttonactiontarget

提问by malthoff

I found some answers to my question but it still does not work. I have setup a button in IB and I want to setup the action and target by code(just for learning). I have a function in my MainViewController:

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

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

In the viewDidLoad function I do this:

在 viewDidLoad 函数中,我这样做:

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

Xcode already marks these lines telling me: "UIButton may not respond to 'setTarget'". When running the app anyways it terminates saying:

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'

That's what I could expect from the XCode warning, but why is that? Every example I find on the web is exactly like mine. Adding the actionMethode to the button via IB works like expected. What am I doing wrong?

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

回答by user784625

first check if you have declared the button as an outlet, second you should check if you connect the outlet to the button or use what I usually do is to add new button in code

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

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

回答by Tendulkar

It may help you.

它可能会帮助你。

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