iOS:单击不同按钮时更改按钮的背景颜色

标签 ios objective-c uibutton

我有一个测验应用程序,它有 4 个答案,其中一个是正确的,它们都在一个 Collection View 中。当用户点击错误答案时,我需要通过更改正确答案的按钮颜色来向他们展示正确答案。我可以访问该按钮,但由于某种原因,按钮颜色没有改变。我错过了什么吗?

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

调试器:好像有颜色

enter image description here

最佳答案

一个简单的解决方案是使用控制变量,当您想要显示正确的解决方案时,您可以更改它并重新加载 Collection View 。类似

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

关于iOS:单击不同按钮时更改按钮的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30383007/

相关文章:

ios - 1% 的时间未处理 UIButton 事件 : who should I blame in my responder chain?

ios - 如何在 iOS/Swift 中创建指定宽度的固定宽度标签?

ios - 从 UserDefaults 加载颜色时应用程序崩溃(Swift)

ios - 我的 Imageview 未在 iPad 中显示?

ios - 为新文档创建路径

swift - 自定义按钮在 Swift 中不起作用

objective-c - 遵循 iOS 教程时找不到特定代码

IOS 在不退出 First Responder 的情况下关闭/显示键盘

iphone - 如何在播放歌曲时在 iOS 中预加载 .mp3?

ios - 无法为 UIButton 添加目标 - 无法识别的选择器发送到实例,尽管方法在同一个类中