fix(training): 优化答题交互并消除按钮置灰闪动

This commit is contained in:
2026-10-14 17:23:34 +08:00
parent 01068bb24e
commit 8c8ba00778
5 changed files with 727 additions and 45 deletions
@@ -10,6 +10,10 @@ final class TrainingExamViewController: TrainingBaseViewController {
private var openedResult = false
private var navigationIsScheduled = false
private var hasAppeared = false
private var isPerformingOperation = false
private var needsReloadOnReturn = false
private var renderedQuestion: TrainingQuestionItem?
private var optionButtons: [String: UIButton] = [:]
private let scrollView = UIScrollView()
private let contentStack = TrainingUI.card()
private let positionLabel = TrainingUI.label(style: .subheadline, color: AppColor.primary)
@@ -48,6 +52,8 @@ final class TrainingExamViewController: TrainingBaseViewController {
navigationStack.distribution = .fillEqually
navigationStack.addArrangedSubview(previousButton)
navigationStack.addArrangedSubview(nextButton)
previousButton.accessibilityIdentifier = "training.exam.previous"
nextButton.accessibilityIdentifier = "training.exam.next"
[positionLabel, questionLabel, hintLabel, optionStack, navigationStack].forEach(contentStack.addArrangedSubview)
bottomStack.axis = .vertical
bottomStack.spacing = 8
@@ -89,18 +95,29 @@ final class TrainingExamViewController: TrainingBaseViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let returning = hasAppeared
let shouldReload = needsReloadOnReturn
needsReloadOnReturn = false
hasAppeared = true
guard !isPerformingOperation, !viewModel.isBusy else { return }
if viewModel.submittedAttempt != nil || viewModel.shouldReturnToCenter {
beginOperation(message: "正在确认考试状态…")
Task { @MainActor in await viewModel.validateIdentity(); finishOperation() }
return
}
if returning, !viewModel.isBusy { loadExam() }
if returning, shouldReload { loadExam() }
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// 自有答题卡和确认弹窗关闭后继续当前题,真实导航返回才刷新考试资格。
if navigationController?.topViewController !== self { needsReloadOnReturn = true }
}
override func onSessionDidExpire() { navigationController?.popToRootViewController(animated: true) }
private func loadExam() {
disableControls()
guard !isPerformingOperation, !viewModel.isBusy else { return }
beginOperation(message: "正在加载试卷…")
Task { @MainActor in
await viewModel.load(service: service, resetDraft: resetDraft)
finishOperation()
@@ -108,10 +125,11 @@ final class TrainingExamViewController: TrainingBaseViewController {
}
private func applyState() {
for child in optionStack.arrangedSubviews { optionStack.removeArrangedSubview(child); child.removeFromSuperview() }
setOperationInteractionEnabled(true)
let pendingTitle = viewModel.hasPendingSubmission ? "恢复交卷结果"
: viewModel.hasPendingMutation ? "重试保存" : viewModel.canRetryCurrentPage ? "重试加载本题" : nil
guard let question = viewModel.currentQuestion else {
clearOptions()
positionLabel.text = ""
questionLabel.text = viewModel.errorMessage ?? (viewModel.hasPendingSubmission ? "正在确认上次交卷结果…" : "正在加载试卷…")
hintLabel.text = ""
@@ -127,29 +145,9 @@ final class TrainingExamViewController: TrainingBaseViewController {
positionLabel.text = "第 \(viewModel.currentIndex + 1) / \(viewModel.questionCount) 题 · \(question.type == .single ? "单选题" : "多选题")"
questionLabel.text = question.stem
hintLabel.text = question.type == .single ? "请选择一个答案" : "请选择所有正确答案,少选、多选、错选均不得分"
for (index, option) in question.options.enumerated() {
let selected = viewModel.currentSelectedIDs.contains(option.id)
let button = UIButton(type: .system)
var configuration = UIButton.Configuration.filled()
configuration.title = "\(TrainingQuestion.optionLetter(index)).\(option.text)"
configuration.baseBackgroundColor = selected ? AppColor.primaryLight : AppColor.pageBackgroundSoft
configuration.baseForegroundColor = selected ? AppColor.primary : AppColor.textPrimary
configuration.contentInsets = NSDirectionalEdgeInsets(top: 18, leading: 16, bottom: 18, trailing: 16)
configuration.image = UIImage(systemName: selected ? "checkmark.circle.fill" : "circle")
configuration.imagePadding = 12
configuration.titleAlignment = .leading
configuration.cornerStyle = .medium
button.configuration = configuration
button.contentHorizontalAlignment = .leading
button.titleLabel?.numberOfLines = 0
button.titleLabel?.lineBreakMode = .byWordWrapping
button.isEnabled = viewModel.canEdit
button.accessibilityIdentifier = "training.option.\(option.id)"
button.accessibilityTraits = selected ? [.button, .selected] : .button
button.addAction(UIAction { [weak self] _ in self?.selectOption(option.id) }, for: .touchUpInside)
optionStack.addArrangedSubview(button)
button.snp.makeConstraints { $0.height.greaterThanOrEqualTo(56) }
}
renderOptions(for: question)
updateOptionSelection(viewModel.currentSelectedIDs)
for button in optionButtons.values { button.isEnabled = viewModel.canEdit }
previousButton.isEnabled = viewModel.canEdit && viewModel.currentIndex > 0
nextButton.isEnabled = viewModel.canEdit && viewModel.currentIndex < viewModel.questionCount - 1
statusLabel.text = viewModel.errorMessage ?? "已答 \(viewModel.answeredCount)/\(viewModel.questionCount) · 答案已保存,可稍后继续"
@@ -158,13 +156,65 @@ final class TrainingExamViewController: TrainingBaseViewController {
submitButton.isEnabled = !viewModel.isBusy && (pendingTitle != nil || viewModel.canEdit)
}
private func disableControls() {
optionStack.arrangedSubviews.compactMap { $0 as? UIButton }.forEach { $0.isEnabled = false }
[previousButton, nextButton, submitButton].forEach { $0.isEnabled = false }
navigationItem.rightBarButtonItem?.isEnabled = false
private func clearOptions() {
for child in optionStack.arrangedSubviews { optionStack.removeArrangedSubview(child); child.removeFromSuperview() }
optionButtons = [:]
renderedQuestion = nil
}
private func renderOptions(for question: TrainingQuestionItem) {
guard renderedQuestion != question else { return }
clearOptions()
renderedQuestion = question
for (index, option) in question.options.enumerated() {
let button = UIButton(type: .system)
var configuration = UIButton.Configuration.filled()
configuration.title = "\(TrainingQuestion.optionLetter(index)).\(option.text)"
configuration.contentInsets = NSDirectionalEdgeInsets(top: 18, leading: 16, bottom: 18, trailing: 16)
configuration.imagePadding = 12
configuration.titleAlignment = .leading
configuration.cornerStyle = .medium
button.configuration = configuration
button.contentHorizontalAlignment = .leading
button.titleLabel?.numberOfLines = 0
button.titleLabel?.lineBreakMode = .byWordWrapping
button.accessibilityIdentifier = "training.option.\(option.id)"
button.addAction(UIAction { [weak self] _ in self?.selectOption(option.id) }, for: .touchUpInside)
optionButtons[option.id] = button
optionStack.addArrangedSubview(button)
button.snp.makeConstraints { $0.height.greaterThanOrEqualTo(56) }
}
}
private func updateOptionSelection(_ selectedIDs: Set<String>) {
UIView.performWithoutAnimation {
for (id, button) in optionButtons {
let selected = selectedIDs.contains(id)
var configuration = button.configuration
configuration?.baseBackgroundColor = selected ? AppColor.primaryLight : AppColor.pageBackgroundSoft
configuration?.baseForegroundColor = selected ? AppColor.primary : AppColor.textPrimary
configuration?.image = UIImage(systemName: selected ? "checkmark.circle.fill" : "circle")
button.configuration = configuration
button.accessibilityTraits = selected ? [.button, .selected] : .button
}
}
}
private func setOperationInteractionEnabled(_ enabled: Bool) {
// 网络操作只暂停动作,保留已启用控件的颜色和透明度。
let buttons: [UIButton] = Array(optionButtons.values) + [previousButton, nextButton, submitButton]
for button in buttons { button.isUserInteractionEnabled = enabled }
}
private func beginOperation(message: String) {
isPerformingOperation = true
setOperationInteractionEnabled(false)
statusLabel.text = message
statusLabel.textColor = AppColor.textSecondary
}
private func finishOperation() {
isPerformingOperation = false
applyState()
scheduleNavigationIfNeeded()
}
@@ -203,8 +253,9 @@ final class TrainingExamViewController: TrainingBaseViewController {
}
private func selectOption(_ id: String) {
guard viewModel.canEdit else { return }
disableControls()
guard !isPerformingOperation, let selected = viewModel.selectionPreview(optionID: id) else { return }
updateOptionSelection(selected)
beginOperation(message: "正在保存答案…")
Task { @MainActor in
await viewModel.select(optionID: id, service: service)
finishOperation()
@@ -212,8 +263,9 @@ final class TrainingExamViewController: TrainingBaseViewController {
}
private func goToQuestion(_ index: Int) {
guard viewModel.canEdit else { return }
disableControls()
guard !isPerformingOperation, viewModel.canEdit,
(0..<viewModel.questionCount).contains(index), index != viewModel.currentIndex else { return }
beginOperation(message: "正在加载题目…")
Task { @MainActor in
await viewModel.goToQuestion(index, service: service)
finishOperation()
@@ -226,7 +278,7 @@ final class TrainingExamViewController: TrainingBaseViewController {
@objc private func nextTapped() { goToQuestion(viewModel.currentIndex + 1) }
@objc private func answerCardTapped() {
guard viewModel.canEdit else { return }
guard !isPerformingOperation, viewModel.canEdit, presentedViewController == nil else { return }
let controller = TrainingAnswerCardViewController(questionCount: viewModel.questionCount,
answeredOrders: viewModel.answeredQuestionOrders, currentIndex: viewModel.currentIndex)
controller.onSelect = { [weak self] index in self?.goToQuestion(index) }
@@ -236,15 +288,15 @@ final class TrainingExamViewController: TrainingBaseViewController {
}
@objc private func submitTapped() {
guard !viewModel.isBusy else { return }
guard !isPerformingOperation, !viewModel.isBusy else { return }
if viewModel.hasPendingMutation {
disableControls()
beginOperation(message: "正在重试保存…")
Task { @MainActor in await viewModel.retryMutation(service: service); finishOperation() }
return
}
if viewModel.hasPendingSubmission { performSubmit(); return }
if viewModel.canRetryCurrentPage {
disableControls()
beginOperation(message: "正在加载题目…")
Task { @MainActor in await viewModel.retryCurrentPage(service: service); finishOperation() }
return
}
@@ -255,6 +307,7 @@ final class TrainingExamViewController: TrainingBaseViewController {
showToast("还有 \(viewModel.questionCount - viewModel.answeredCount) 道题未作答,已定位到第一道")
return
}
guard presentedViewController == nil else { return }
let alert = UIAlertController(title: "确认交卷?", message: "已完成 \(viewModel.questionCount) 道题,提交后将生成本次考试记录。", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "继续检查", style: .cancel))
alert.addAction(UIAlertAction(title: "交卷", style: .default) { [weak self] _ in self?.performSubmit() })
@@ -262,7 +315,8 @@ final class TrainingExamViewController: TrainingBaseViewController {
}
private func performSubmit() {
disableControls()
guard !isPerformingOperation, !viewModel.isBusy else { return }
beginOperation(message: "正在提交并确认成绩…")
Task { @MainActor in
_ = await viewModel.submit(service: service)
finishOperation()