ios - 在 IBAction 中按下时为 UIButtons 显示不同的颜色以进行测验

标签 ios objective-c xcode if-statement uibutton

我有四个 UIButtons 代表 4 个答案。我已经设法将所有内容连接起来,并以绿色显示正确答案,以红色显示错误答案。

我唯一的问题是,当用户选择错误答案时,我会将所有答案灰显。我也想向用户展示正确答案。我试过 else if 语句但遗漏了一些东西,有什么建议吗?

-(IBAction)Answer1:(id)sender{

    if (Answer1Correct == YES) {
        [Answer1 setTitle:@"Correct" forState:UIControlStateNormal];
        [Answer1 setBackgroundColor:[UIColor greenColor]];
        [self RightAnswer];
    }
    else{

        [Answer1 setBackgroundColor:[UIColor redColor]];
        [Answer1 setTitle:@"Incorrect" forState:UIControlStateNormal];
        [Answer2 setBackgroundColor:[UIColor colorWithRed:102.0/255.0 green:102.0/255.0 blue:102.0/255.0 alpha:1.0f]];
        [Answer3 setBackgroundColor:[UIColor colorWithRed:102.0/255.0 green:102.0/255.0 blue:102.0/255.0 alpha:1.0f]];
        [Answer4 setBackgroundColor:[UIColor colorWithRed:102.0/255.0 green:102.0/255.0 blue:102.0/255.0 alpha:1.0f]];
        [self WrongAnswer];
    }
}

最佳答案

最好的方法是继承UIButton。创建类 QuizQuestionButton 这个类将有方法 -setCorrectAnswer:(NSString *)correctAnswer-setRealAnswer:(NSString *)realAnswer

如果两者相同 - 将背景颜色设置为绿色,否则设置为红色。

-(void)setCorrectAnswer:(NSString *)correctAnswer {
     _correctAnswer = correctAnswer;
}

-(void)setRealAnswer:(NSString *)realAnswer {
    if (realAnswer == _correctAnswer) {
        self.backgroundColor = [UIColor greenColor];
    } else {
        self.backgroundColor = [UIColor redColor];
    }
}

另请阅读设计模式 - 策略。此模式可以帮助您避免 if-else 语句。

关于ios - 在 IBAction 中按下时为 UIButtons 显示不同的颜色以进行测验,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29008647/

相关文章:

ios - 我如何从 HKHealthStore 中删除多个对象?

ios - 检查 UIWebView 的 URL

iphone - 如何删除 box2d Fixture

javascript - 如何在 ReactJS 中导入 ActivityIndi​​catorIOS?

iphone - iOS5 ARC 应用程序 : __NSAutoreleaseNoPool(): of class NSCFNumber autoreleased with no pool in place - just leaking

ios - 如何在IOS中实现输入文本框作为必填字段

ios - 应用程序从后台返回时黑屏

ios - NSMutableArray ReplaceObjectAtIndex 崩溃

objective-c - iOS 应用程序可以访问设备视频库中视频的字幕或隐藏式字幕吗?

objective-c - Objective-C 中的 @ 运算符是否与 C 中的 & 运算符相同?