2011-06-30 10 views
1

私はUIButtonにアクションを追加しようとしているが、例外得続ける午前にIBActionを追加しようとすると:キャッチされない例外により「NSInvalidArgumentException」にiPhone - プログラム的にUIButton

アプリを終了し、理由:「[UIImageView addTarget:アクションは:forControlEventsは:]:

- (void)viewDidLoad 
{ 

    [super viewDidLoad]; 


    UIImage *myIcon = [UIImage imageNamed:@"Icon_Profile"]; 
    self.profileButton = (UIButton*)[[UIImageView alloc] initWithImage:myIcon]; 

    [self.profileButton addTarget:self action:@selector(profileButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; 

    UIBarButtonItem *buttonItem = [[[UIBarButtonItem alloc] initWithCustomView:profileButton] autorelease]; 

    NSArray *toolbarItems = [[NSArray alloc] initWithObjects:buttonItem, nil]; 

    [self setToolbarItems:toolbarItems animated:NO]; 

    //[toolbarItems release]; 
    //[profileButton release]; 
    } 

そしてI H:未認識セレクタはインスタンス0x595fba0' に

を送信ここに私のコードであります同じビューコントローラでは、この方法をaveの:

-(void)profileButtonPressed:(id)sender{ 

} 

とヘッダに私は

-(IBAction)profileButtonPressed:(id)sender; 

を持って起こっていただきました!私は知りません。任意の助けに感謝:)

答えて

2

を作成することができます

このような
- (void)buttonPlayClick:(UIButton*)sender{ 
} 

する必要がありますUIButtonのように動作することを期待してください。 UIBarButtonItemを作成する予定であるため、initWithImage:style:target:action:を使用して画像で初期化してください。

UIBarButtonItem *buttonItem = [[[UIBarButtonItem alloc] initWithImage:myIcon style:UIBarButtonItemStylePlain target:self action:@selector(profileButtonPressed:)] autorelease]; 

私は、これはUIButtonを作成し、カスタムビューとして、それを割り当てる以上のより良いアプローチだと思います。

+0

パーフェクト。みんな助けてくれてありがとう。 – shaw2thefloor

2

これは非常に間違っになります

self.profileButton = (UIButton*)[[UIImageView alloc] initWithImage:myIcon]; 

UIImageViewUIButtonではありません。あなたはallocinit適切UIButton必要があり、あなたがボタンにUIImageViewをキャストしているなぜ、あなたは

[self.profileButton setImage: myIcon forState:UIControlStateNormal]; 
3

を呼び出すことができます。

UIImage *myIcon = [UIImage imageNamed:@"Icon_Profile"]; 
self.profileButton = [UIButton buttonWithStyle:UIButtonStyleCustom]; 
[self.profileButton setImage:myIcon forState:UIControlStateNormal]; 
[self.profileButton addTarget:self action:@selector(profileButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; 
+0

setImage:またはsetImage:forState:? – taskinoor

+0

申し訳ありません私の悪い... – iPrabu

4

あなたはaddTarget:action:forControlEvents:に応答しないUIButtonからUIImageViewをキャストしています。 setBackgroundImage:forState:またはsetImage:forState:UIButtonを使用して、実際のボタンを作成し、さまざまな状態の画像を設定します。

2

最初に独自のボタンを作成します。そして、後にアクションを追加します。

UIImage *myIcon = [UIImage imageNamed:@"Icon_Profile"]; 
UIButton *buttonPlay = [UIButton buttonWithType:UIButtonTypeCustom]; 
buttonPlay.frame = CGRectMake(0, 0, 20, 20); 
[buttonPlay setBackgroundImage:myIcon forState:UIControlStateNormal]; 
[buttonPlay addTarget:self action:@selector(buttonPlayClick:) forControlEvents:UIControlEventTouchUpInside]; 

そして、あなたのセレクタは、今、あなたはあなたがUIButtonUIImageViewオブジェクトをキャストすることはできませんカスタムバーの項目

UIBarButtonItem *buttonItem = [[[UIBarButtonItem alloc] initWithCustomView:buttonPlay] autorelease]; 
関連する問題