0

ユーザーがタッチした瞬間に画像が黄色に変わるようにします。現在、最初のタップで画像が少し灰色になり、離すと黄色に変わります。画像を 2 回タップすると、すぐに赤に戻ります。どうすればこれを修正できますか?

-(void)bMethod:(UIButton*)sender
{
    sender.selected = !sender.selected;    
}

- (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:UIControlEventTouchDown];
    [myButton setImage:buttonImage forState:UIControlStateNormal];
    [myButton setImage:buttonImageSelected forState:UIControlStateSelected];
    [myButton setImage:buttonImageSelected forState:UIControlStateHighlighted];
    [self.view addSubview:myButton];
4

1 に答える 1

1

私はあなたのコードを実行しましたが、うまくいっています。画像の名前をもう一度確認してください。

編集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];
}
于 2013-05-07T09:30:10.967 に答える