添加动作以编程方式创建UIButton

1 cocoa-touch objective-c ios

这是我的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
Run Code Online (Sandbox Code Playgroud)

这是ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController {

}

- (IBAction)close:(id)sender;

@end
Run Code Online (Sandbox Code Playgroud)

一切都很简单,但我一直收到这个错误:

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

非常莫名其妙!

Gar*_*ary 5

您需要将aMethod添加到ViewController类.

- (void)aMethod:(id)sender
{
}
Run Code Online (Sandbox Code Playgroud)