Asif Alamgir
Asif Alamgir

Reputation: 1462

iOS: Change background color of a button when different button is clicked

I have quiz app which has 4 answers and one of them is right and they are all within a collection view. When a user clicks the wrong answer, I need to show them the right answer by changing button color for the right answer. I got access to that button but for some reason, the button color is not changing. Am I missing something?

-(void)selectedAnswer:(UIButton *)sender{
    NSLog(@"ANswer Selected : %ld",(long)sender.tag);
    NSLog(@"CurrentAnswer : %@",_currentAnswer);
    NSLog(@"Question : %@",[[GameManager manager] getCurrentQuestion]);
    int correctAnswer = [[_currentAnswer stringByReplacingOccurrencesOfString:@" " withString:@""] intValue];
    NSLog(@"Correct Answer Is : %d",correctAnswer);
    if (correctAnswer == sender.tag){
        NSLog(@"Correct Answer Index : %@",_currentAnswerIndex);
        sender.backgroundColor = [UIColor greenColor];

        //[self updateScore:true];
        //[self nextQuestion];
    }else{
          NSLog(@"Correct Answer Index : %@",_currentAnswerIndex);
        sender.backgroundColor = [UIColor redColor];
        SignCollectionViewCell * cell = (SignCollectionViewCell *)[self collectionView:self._collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:[_currentAnswerIndex integerValue] inSection:0]];
        NSLog(@"cell Tag %@",cell.answerButton);

        cell.answerButton.backgroundColor = [UIColor greenColor];//NOT WORKING
       // [self updateScore:false];
        //[self nextQuestion];
    }
}

Debugger: Color seems to be there

enter image description here

Upvotes: 0

Views: 954

Answers (1)

rob180
rob180

Reputation: 901

One easy solution is to use a control variable, and when you want to show the correct solution you change it and reload the collection view. something like

if(shouldShowAnswer){
  cell.answerButton.backgroundColor = [UIColor greenColor]
}else{
  cell.answerButton.backgroundColor = defaultColor
}

Upvotes: 2

Related Questions