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

时间:2013-08-27 23:21:31

标签: ios objective-c cocoa-touch

这是我的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'

非常莫名其妙!

3 个答案:

答案 0 :(得分:5)

您需要向ViewController类添加一个方法。

- (void)aMethod:(id)sender
{
}

答案 1 :(得分:2)

虽然很简单,ViewController没有实现-aMethod:

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

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

会导致aMethod:上的self触发按钮上的触碰事件。

由于您尚未实施此类方法,因此会崩溃。一点也不困惑。

答案 2 :(得分: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;

您粘贴的代码将开始工作