SwiftUI问答按钮点击后颜色显示异常,需设置1秒高亮时长
问题修复方案
第一步:解决背景色叠加问题
ChoiceTextView自带的蓝色背景和你在ContentView中添加的背景会叠加,导致颜色显示异常。我们重构ChoiceTextView,让它支持外部传入背景色,彻底消除叠加问题:
struct ChoiceTextView: View { let choiceText: String var backgroundColor: Color = .blue // 默认蓝色,可外部覆盖 var body: some View { Text(choiceText) .font(.title) .foregroundColor(.white) .frame(width: UIScreen.main.bounds.width - 100, height: 100) .background( RoundedRectangle(cornerRadius: 10) .fill(backgroundColor) ) } }
第二步:实现点击后颜色保持1秒的效果
在ContentView中,通过状态变量控制选中状态,配合延时逻辑让结果颜色持久显示,同时简化按钮布局代码:
// 假设你的ContentView已声明以下状态变量 @State private var selectedAnswerIndex: Int? // ... ForEach(0..<question.possibleAnswers.count) { answerIndex in Button(action: { selectedAnswerIndex = answerIndex // 延迟1秒重置选中状态,恢复默认样式 DispatchQueue.main.asyncAfter(deadline: .now() + 1) { selectedAnswerIndex = nil } checkAnswer(answerIndex) }, label: { ChoiceTextView( choiceText: question.possibleAnswers[answerIndex], backgroundColor: getButtonColor(for: answerIndex) ) .padding(5) }) } // 提取颜色判断逻辑,让代码更清晰 private func getButtonColor(for index: Int) -> Color { guard let selectedIndex = selectedAnswerIndex else { return .blue // 未选中时显示默认蓝色 } return index == selectedIndex ? (index == question.correctAnswer ? .green : .red) : .blue }
可选优化:添加平滑过渡动画
如果想让颜色切换更自然,给ChoiceTextView加上动画效果:
ChoiceTextView( choiceText: question.possibleAnswers[answerIndex], backgroundColor: getButtonColor(for: answerIndex) ) .padding(5) .animation(.easeInOut(duration: 0.2), value: selectedAnswerIndex)
核心逻辑说明
- 重构后的
ChoiceTextView将背景色的控制权交给父视图,彻底解决多层背景叠加导致的颜色异常问题。 - 通过
selectedAnswerIndex记录用户选中的选项,配合DispatchQueue延时重置状态,确保结果颜色能稳定显示1秒。 - 提取颜色判断方法,让按钮样式逻辑更清晰,便于后续维护。
内容的提问来源于stack exchange,提问作者Poshin
相关产品推荐
相关产品推荐

