0

UIButton にアクションを追加しようとしていますが、例外が発生し続けます:

キャッチされない例外 'NSInvalidArgumentException' によるアプリの終了、理由: '[UIImageView addTarget:action:forControlEvents:]: 認識されないセレクターがインスタンス 0x595fba0 に送信されました'

これが私のコードです:

- (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];
}

次に、同じViewコントローラーにこのメソッドがあります:

-(void)profileButtonPressed:(id)sender{

}

そして、私が持っているヘッダーに

-(IBAction)profileButtonPressed:(id)sender;

どうしたの?

4

5 に答える 5

4

に応答しない をキャストしUIImageViewています。またはを使用して、実際のボタンを作成し、さまざまな状態のイメージを設定します。UIButtonaddTarget:action:forControlEvents:setBackgroundImage:forState:setImage:forState:UIButton

于 2011-06-30T12:41:03.477 に答える
3

UIImageView をボタンにキャストするのはなぜですか。

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];
于 2011-06-30T12:40:18.227 に答える
2

これは非常に間違っているように見えます:

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

AUIImageViewは ではありませんUIButton。あなたは適切な、allocそしてあなたは呼び出すことができますinitUIButton

[self.profileButton setImage: myIcon forState:UIControlStateNormal];
于 2011-06-30T12:39:55.637 に答える
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];

そして、セレクターは次のようになります

- (void)buttonPlayClick:(UIButton*)sender{
}

カスタム バー アイテムを作成できるようになりました

UIBarButtonItem *buttonItem = [[[UIBarButtonItem alloc] initWithCustomView:buttonPlay] autorelease];
于 2011-06-30T12:41:23.997 に答える
2

UIImageViewオブジェクトを にキャストして、 のUIButtonように動作することを期待することはできませんUIButton。を作成するつもりなのでUIBarButtonItem、 を使用initWithImage:style:target:action:してイメージで初期化します。

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

UIButtonこれは、を作成してカスタム ビューとして割り当てるよりも優れたアプローチだと思います。

于 2011-06-30T12:43:45.300 に答える