私はあなたのコードを実行しましたが、うまくいっています。画像の名前をもう一度確認してください。
編集1:
コードを次のように置き換えます。
-(void)bMethod:(UIButton*)sender
{
if (sender.imageView.image != [UIImage imageNamed:@"red.png"]){
[sender setImage:[UIImage imageNamed:@"yellow.png"] forState:UIControlStateHighlighted];
[sender setImage:[UIImage imageNamed:@"yellow.png"] forState:UIControlStateNormal];
}
else{
[sender setImage:[UIImage imageNamed:@"red.png"] forState:UIControlStateHighlighted];
[sender setImage:[UIImage imageNamed:@"red.png"] forState:UIControlStateNormal];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *buttonImage = [UIImage imageNamed:@"red.png"];
myButton.frame = CGRectMake(200, 200, 40, 40);
[myButton addTarget:self action:@selector(bMethod:) forControlEvents:UIControlEventTouchDown];
[myButton setImage:buttonImage forState:UIControlStateNormal];
[self.view addSubview:myButton];
}
編集2:
-(void)bMethod:(UIButton*)sender
{
sender.selected = !sender.selected;
sender.highlighted = !sender.highlighted;
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *buttonImage = [UIImage imageNamed:@"red.png"];
UIImage *buttonImageSelected = [UIImage imageNamed:@"yellow.png"];
myButton.frame = CGRectMake(200, 200, 40, 40);
[myButton addTarget:self action:@selector(bMethod:) forControlEvents:UIControlEventTouchUpInside];
myButton.adjustsImageWhenHighlighted = NO;
[myButton setImage:buttonImage forState:UIControlStateNormal];
[myButton setImage:buttonImageSelected forState:UIControlStateSelected];
[myButton setImage:buttonImageSelected forState:UIControlStateHighlighted];
[self.view addSubview:myButton];
}