2013-08-27 34 views
1

這裏是我的ViewController.m添加行爲的UIButton

#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:]: unrecognized selector sent to instance 0x7141780 Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ViewController aMethod:]: unrecognized selector sent to instance 0x7141780'

非常莫名其妙!

回答

5

您需要將aMethod添加到您的ViewController類。

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

是的。謝謝!! –

2

至於因爲它得到簡單,ViewController不執行-aMethod:

我想你錯過了複製粘貼,你應該改變選擇器。

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

會造成aMethod:self火上向下觸摸按鈕事件。

由於您尚未實施此類方法,因此會發生崩潰。一點都不困惑。

+0

愚蠢的我。謝謝!! –

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; 

您的代碼粘貼在問題將開始工作,當然