1

这是我的 ViewController.m 代码

#import "ViewController.h"

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self addMyButton];
}

-(void)addMyButton {
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];

    webView.tag=55;
    NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    [webView loadRequest:requestObj];
    [self.view addSubview:webView];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button addTarget:self
               action:@selector(aMethod:)
    forControlEvents:UIControlEventTouchDown];

    [button setTitle:@"Close" forState:UIControlStateNormal];
    button.frame = CGRectMake(80, 210, 160, 40);
    [button addTarget:self action:@selector(close:) forControlEvents:UIControlEventTouchUpInside];
    [webView addSubview:button];
}

- (IBAction)close:(id)sender {
   // [[self.view viewWithTag:55] removeFromSuperview];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [super dealloc];
}
@end

这是 ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController {

}

- (IBAction)close:(id)sender;

@end

一切都非常简单,但我不断收到此错误:

-[ViewController aMethod:]:无法识别的选择器发送到实例 0x7141780 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[ViewController aMethod:]:无法识别的选择器发送到实例 0x7141780”

很莫名其妙!

4

3 回答 3

5

您需要将 aMethod 添加到您的 ViewController 类。

- (void)aMethod:(id)sender
{
}
于 2013-08-27T23:27:33.303 回答
2

很简单,ViewController就是不实现-aMethod:.

我认为您错过了复制粘贴,您应该更改选择器。

[button addTarget:self
           action:@selector(aMethod:)
 forControlEvents:UIControlEventTouchDown];

将导致aMethod:onself触发按钮上的触地事件。

由于您尚未实现此类方法,因此您会崩溃。一点都不莫名其妙。

于 2013-08-27T23:28:42.753 回答
0
[button addTarget:self  action:@selector(aMethod:)forControlEvents:UIControlEventTouchDown];

[button addTarget:self action:@selector(close:) forControlEvents:UIControlEventTouchUpInside];

您的代码清楚地表明您正在添加两个目标。删除第一个

[button addTarget:self  action:@selector(aMethod:)forControlEvents:UIControlEventTouchDown];

并使用你的

- (IBAction)close:(id)sender;

您粘贴的有问题的代码将开始工作

于 2013-08-28T04:35:55.773 回答