feat(training): 新增培训中心学习答题演示及成绩回顾

新增首页和个人页培训入口,支持课程阅读、答题卡、未交卷答案恢复、成绩记录及重考。
对齐小程序的培训首页与成绩页,答案解析默认收起并提供返回对应课程的入口。

开发版使用隔离的本机演示数据,正式培训服务尚未接入。
This commit is contained in:
han xin
2026-10-10 11:36:49 +08:00
parent e1175066b9
commit 74c451c5e5
17 changed files with 2612 additions and 7 deletions
@@ -30,6 +30,7 @@ final class ProfileViewController: BaseViewController {
private let realNameRow = ProfileInfoRowView(title: "认证状态")
private let statusRow = ProfileInfoRowView(title: "账号状态")
private let scenicRow = ProfileInfoRowView(title: "当前景区")
private let trainingRow = ProfileInfoRowView(title: "培训中心")
private let settingRow = ProfileInfoRowView(title: "设置中心")
private let logoutButton = UIButton(type: .system)
private var hasLoadedProfileOnce = false
@@ -92,6 +93,7 @@ final class ProfileViewController: BaseViewController {
withdrawalRow.addTarget(self, action: #selector(withdrawalTapped), for: .touchUpInside)
realNameRow.addTarget(self, action: #selector(realNameTapped), for: .touchUpInside)
settingRow.addTarget(self, action: #selector(settingTapped), for: .touchUpInside)
trainingRow.addTarget(self, action: #selector(trainingTapped), for: .touchUpInside)
NotificationCenter.default.addObserver(
self,
@@ -183,7 +185,7 @@ final class ProfileViewController: BaseViewController {
[
nameRow, accountRow, phoneRow, withdrawalRow,
passwordRow, realNameRow, statusRow, scenicRow,
settingRow
trainingRow, settingRow
].forEach { infoCard.addArrangedSubview($0) }
nameRow.isUserInteractionEnabled = false
@@ -202,6 +204,7 @@ final class ProfileViewController: BaseViewController {
}
private func applyViewModel() {
trainingRow.configure(value: "学习课程与答题", accessory: .chevron)
nicknameField.text = viewModel.displayNickname
uidLabel.text = "UID:\(viewModel.displayUID)"
avatarImageView.loadRemoteImage(urlString: viewModel.displayAvatarURL)
@@ -353,6 +356,10 @@ final class ProfileViewController: BaseViewController {
navigationController?.pushViewController(SettingViewController(), animated: true)
}
@objc private func trainingTapped() {
HomeRouteHandler.open(uri: "/training", from: self, storeItem: nil)
}
@objc private func logoutTapped() {
let alert = UIAlertController(title: "确定退出登录?", message: "退出后将需要重新登录", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "取消", style: .cancel))
@@ -0,0 +1,298 @@
import SnapKit
import UIKit
/// 培训首页、完整任务列表和考试记录共用一个页面,与小程序入口保持一致。
@MainActor
final class TrainingCenterViewController: TrainingBaseViewController {
private enum Item: Hashable { case task(String), attempt(taskID: String, attemptID: String) }
private let service: any TrainingServing
private let viewModel = TrainingCenterViewModel()
private let tableView = UITableView(frame: .zero, style: .plain)
private let refreshControl = UIRefreshControl()
private let header = UIStackView()
private let hero = UIStackView()
private let greetingLabel = TrainingUI.text(size: 14, color: .white)
private let titleLabel = TrainingUI.text("我的培训中心", size: 18, weight: .bold, color: .white)
private var statLabels: [UILabel] = []
private let headingLabel = TrainingUI.text(size: 15.5, weight: .semibold)
private let viewAllButton = TrainingUI.button("查看全部", plain: true)
private let filters = UIStackView()
private var filterButtons: [UIButton] = []
private let searchField = UITextField()
private let tabBar = UIStackView()
private let tabBackground = UIView()
private var tabButtons: [UIButton] = []
private let footer = UIStackView()
private let stateLabel = TrainingUI.text(size: 14, color: TrainingUI.muted)
private let retryButton = TrainingUI.button("重新加载", secondary: true)
private let moreButton = TrainingUI.button("加载更多记录", plain: true)
private var dataSource: UITableViewDiffableDataSource<Int, Item>!
/// 默认连接正式服务,开发演示仅由用户显式打开。
init(service: any TrainingServing = TrainingServiceFactory.production(), showsHistory: Bool = false) {
self.service = service
viewModel.tab = showsHistory ? .records : .home
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func setupNavigationBar() {
TrainingUI.navigation(self, title: "培训中心")
#if DEBUG
if !service.isDemo { navigationItem.rightBarButtonItem = UIBarButtonItem(title: "开发演示", style: .plain, target: self, action: #selector(demoTapped)) }
#endif
}
override func setupUI() {
view.backgroundColor = TrainingUI.background
header.axis = .vertical
header.spacing = 0
hero.axis = .vertical
hero.spacing = 8
hero.backgroundColor = UIColor(red: 45/255, green: 128/255, blue: 250/255, alpha: 1)
hero.layer.cornerRadius = 14
hero.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
hero.isLayoutMarginsRelativeArrangement = true
hero.layoutMargins = UIEdgeInsets(top: 19, left: 17, bottom: 18, right: 17)
hero.addArrangedSubview(greetingLabel)
hero.addArrangedSubview(titleLabel)
let stats = UIStackView()
stats.distribution = .fillEqually
stats.alignment = .fill
for caption in ["待考试", "已完成", "最近得分"] {
let value = TrainingUI.text("—", size: 23, weight: .bold, color: .white)
value.textAlignment = .center
statLabels.append(value)
let name = TrainingUI.text(caption, size: 12.5, color: .white)
name.textAlignment = .center
let column = UIStackView(arrangedSubviews: [value, name])
column.axis = .vertical
column.spacing = 6
stats.addArrangedSubview(column)
if statLabels.count > 1 {
let line = UIView()
line.backgroundColor = UIColor.white.withAlphaComponent(0.4)
column.addSubview(line)
line.snp.makeConstraints { $0.leading.top.bottom.equalToSuperview(); $0.width.equalTo(1) }
}
}
hero.setCustomSpacing(18, after: titleLabel)
hero.addArrangedSubview(stats)
header.addArrangedSubview(hero)
let body = UIStackView()
body.axis = .vertical
body.spacing = 11
body.isLayoutMarginsRelativeArrangement = true
body.layoutMargins = UIEdgeInsets(top: 14, left: 13, bottom: 10, right: 13)
if service.isDemo { body.addArrangedSubview(TrainingUI.demoNotice()) }
let heading = UIStackView(arrangedSubviews: [headingLabel, viewAllButton])
heading.alignment = .center
heading.spacing = 8
headingLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
viewAllButton.setContentHuggingPriority(.required, for: .horizontal)
body.addArrangedSubview(heading)
filters.distribution = .fillEqually
filters.spacing = 9
for state in TrainingLearnerStatus.allCases {
let button = TrainingUI.button(state.title, secondary: true)
button.tag = state == .pendingExam ? 0 : 1
button.accessibilityIdentifier = "training.filter.\(button.tag)"
button.addTarget(self, action: #selector(filterTapped(_:)), for: .touchUpInside)
filterButtons.append(button)
filters.addArrangedSubview(button)
}
body.addArrangedSubview(filters)
searchField.font = .systemFont(ofSize: 13)
searchField.backgroundColor = .white
searchField.layer.cornerRadius = 8
searchField.placeholder = "搜索任务或课程名称"
searchField.clearButtonMode = .whileEditing
searchField.returnKeyType = .search
searchField.accessibilityIdentifier = "training.search"
searchField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 12, height: 1))
searchField.leftViewMode = .always
searchField.snp.makeConstraints { $0.height.equalTo(44) }
body.addArrangedSubview(searchField)
header.addArrangedSubview(body)
tableView.backgroundColor = .clear
tableView.separatorStyle = .none
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 250
tableView.delegate = self
tableView.keyboardDismissMode = .onDrag
tableView.refreshControl = refreshControl
tableView.register(TrainingTaskCell.self, forCellReuseIdentifier: TrainingTaskCell.reuseIdentifier)
tableView.register(TrainingRecordCell.self, forCellReuseIdentifier: TrainingRecordCell.reuseIdentifier)
tableView.tableHeaderView = header
footer.axis = .vertical
footer.spacing = 12
footer.isLayoutMarginsRelativeArrangement = true
footer.layoutMargins = UIEdgeInsets(top: 24, left: 26, bottom: 24, right: 26)
stateLabel.textAlignment = .center
[stateLabel, retryButton, moreButton].forEach(footer.addArrangedSubview)
tableView.tableFooterView = footer
tabBackground.backgroundColor = .white
let line = UIView()
line.backgroundColor = TrainingUI.border
tabBackground.addSubview(line)
line.snp.makeConstraints { $0.top.leading.trailing.equalToSuperview(); $0.height.equalTo(1) }
tabBar.distribution = .fillEqually
for tab in TrainingCenterTab.allCases {
let button = TrainingUI.button(tab.title, plain: true)
button.tag = tab.rawValue
button.accessibilityIdentifier = "training.tab.\(tab.rawValue)"
button.addTarget(self, action: #selector(tabTapped(_:)), for: .touchUpInside)
tabButtons.append(button)
tabBar.addArrangedSubview(button)
}
view.addSubview(tableView)
view.addSubview(tabBackground)
tabBackground.addSubview(tabBar)
configureDataSource()
applyState()
}
override func setupConstraints() {
tabBackground.snp.makeConstraints { $0.leading.trailing.bottom.equalToSuperview() }
tabBar.snp.makeConstraints {
$0.leading.trailing.equalToSuperview().inset(12)
$0.top.equalToSuperview().offset(7)
$0.bottom.equalTo(view.safeAreaLayoutGuide).offset(-7)
}
tableView.snp.makeConstraints {
$0.top.leading.trailing.equalTo(view.safeAreaLayoutGuide)
$0.bottom.equalTo(tabBackground.snp.top)
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
sizeTableSupplementaryViews()
}
private func sizeTableSupplementaryViews() {
let width = tableView.bounds.width
guard width > 0 else { return }
for stack in [header, footer] {
let height = stack.systemLayoutSizeFitting(CGSize(width: width, height: 0), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel).height
if abs(stack.frame.height - height) > 0.5 || stack.frame.width != width {
stack.frame = CGRect(x: 0, y: 0, width: width, height: height)
if stack === header { tableView.tableHeaderView = header } else { tableView.tableFooterView = footer }
}
}
}
override func bindActions() {
refreshControl.addTarget(self, action: #selector(reloadTapped), for: .valueChanged)
retryButton.addTarget(self, action: #selector(reloadTapped), for: .touchUpInside)
viewAllButton.addTarget(self, action: #selector(viewAllTapped), for: .touchUpInside)
searchField.addTarget(self, action: #selector(searchChanged), for: .editingChanged)
moreButton.addTarget(self, action: #selector(moreTapped), for: .touchUpInside)
}
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated); reloadTapped() }
override func onSessionDidExpire() { navigationController?.popToRootViewController(animated: true) }
private func configureDataSource() {
dataSource = UITableViewDiffableDataSource<Int, Item>(tableView: tableView) { [weak self] table, indexPath, item in
guard let self else { return nil }
switch item {
case .task(let id):
guard let task = self.viewModel.tasks.first(where: { $0.id == id }), let cell = table.dequeueReusableCell(withIdentifier: TrainingTaskCell.reuseIdentifier, for: indexPath) as? TrainingTaskCell else { return nil }
cell.configure(task: task)
cell.onAction = { [weak self] in self?.openTask(task, directAction: true) }
return cell
case .attempt(let taskID, let attemptID):
guard let task = self.viewModel.tasks.first(where: { $0.id == taskID }), let attempt = task.progress.attempts.first(where: { $0.id == attemptID }), let cell = table.dequeueReusableCell(withIdentifier: TrainingRecordCell.reuseIdentifier, for: indexPath) as? TrainingRecordCell else { return nil }
cell.configure(task: task, attempt: attempt)
return cell
}
}
}
private func applyState() {
let session = AppStore.shared.session
let name = [session.realName, session.userName].first { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } ?? "当前学员"
greetingLabel.text = "你好,\(name)"
let context = session.currentScenicName.trimmingCharacters(in: .whitespacesAndNewlines)
titleLabel.text = context.isEmpty ? "我的培训中心" : "\(context) · 培训中心"
for (label, value) in zip(statLabels, [String(viewModel.pendingCount), String(viewModel.completedCount), viewModel.latestScore]) { label.text = value }
headingLabel.text = switch viewModel.tab { case .home: "新政策与必读内容"; case .tasks: "我的学习任务"; case .records: "考试记录" }
viewAllButton.isHidden = viewModel.tab != .home
filters.isHidden = viewModel.tab != .tasks
searchField.isHidden = viewModel.tab != .tasks
for (index, button) in filterButtons.enumerated() {
var configuration = button.configuration
configuration?.title = index == 0 ? "待考试 \(viewModel.pendingCount)" : "已完成 \(viewModel.completedCount)"
configuration?.background.backgroundColor = index == (viewModel.filter == .pendingExam ? 0 : 1) ? TrainingUI.primary.withAlphaComponent(0.09) : .white
configuration?.baseForegroundColor = index == (viewModel.filter == .pendingExam ? 0 : 1) ? TrainingUI.primary : TrainingUI.muted
button.configuration = configuration
}
for (index, button) in tabButtons.enumerated() {
var configuration = button.configuration
configuration?.baseForegroundColor = index == viewModel.tab.rawValue ? TrainingUI.primary : TrainingUI.muted
button.configuration = configuration
button.accessibilityTraits = index == viewModel.tab.rawValue ? [.button, .selected] : .button
}
let items: [Item] = viewModel.tab == .records ? viewModel.records.prefix(viewModel.recordLimit).map { .attempt(taskID: $0.task.id, attemptID: $0.attempt.id) } : viewModel.visibleTasks.map { .task($0.id) }
var snapshot = NSDiffableDataSourceSnapshot<Int, Item>()
snapshot.appendSections([0])
snapshot.appendItems(items)
snapshot.reconfigureItems(items.filter { dataSource.snapshot().indexOfItem($0) != nil })
dataSource.apply(snapshot, animatingDifferences: false)
stateLabel.text = viewModel.errorMessage ?? (viewModel.isLoading ? "正在加载培训任务…" : viewModel.tab == .records ? "暂无考试记录\n交卷后可在此查看成绩和解析" : "暂无符合条件的任务\n景区分配给当前账号的任务会显示在这里")
stateLabel.isHidden = !items.isEmpty
retryButton.isHidden = viewModel.errorMessage == nil
retryButton.isEnabled = !viewModel.isLoading
moreButton.isHidden = viewModel.tab != .records || viewModel.records.count <= viewModel.recordLimit
if !viewModel.isLoading { refreshControl.endRefreshing() }
sizeTableSupplementaryViews()
}
/// 页面出现和下拉刷新都读取最新本人任务。
func reload() async { await viewModel.load(service: service); applyState() }
/// 在同一页面切换入口,返回课程时保留筛选上下文。
func selectTab(_ tab: TrainingCenterTab) {
view.endEditing(true)
viewModel.selectTab(tab)
searchField.text = ""
applyState()
tableView.setContentOffset(.zero, animated: false)
}
@objc private func reloadTapped() {
guard !viewModel.isLoading else { return }
Task { @MainActor in await reload() }
}
@objc private func tabTapped(_ button: UIButton) { if let tab = TrainingCenterTab(rawValue: button.tag) { selectTab(tab) } }
@objc private func filterTapped(_ button: UIButton) { viewModel.filter = button.tag == 0 ? .pendingExam : .completed; applyState() }
@objc private func searchChanged() { viewModel.keyword = searchField.text ?? ""; applyState() }
@objc private func moreTapped() { viewModel.recordLimit += 20; applyState() }
@objc private func viewAllTapped() { viewModel.filter = .pendingExam; selectTab(.tasks) }
#if DEBUG
@objc private func demoTapped() {
do { navigationController?.pushViewController(TrainingCenterViewController(service: try TrainingServiceFactory.demo()), animated: true) }
catch { showToast(error.localizedDescription) }
}
#endif
private func openTask(_ task: TrainingTask, directAction: Bool) {
let controller: UIViewController = directAction && TrainingTaskPresentation(task: task).canStartExam ? TrainingExamViewController(taskID: task.id, service: service) : TrainingCourseViewController(taskID: task.id, service: service)
navigationController?.pushViewController(controller, animated: true)
}
}
extension TrainingCenterViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard let item = dataSource.itemIdentifier(for: indexPath) else { return }
switch item {
case .task(let id): if let task = viewModel.tasks.first(where: { $0.id == id }) { openTask(task, directAction: false) }
case .attempt(let taskID, let attemptID): navigationController?.pushViewController(TrainingResultViewController(taskID: taskID, attemptID: attemptID, service: service), animated: true)
}
}
}
@@ -0,0 +1,238 @@
import SafariServices
import SnapKit
import UIKit
import WebKit
/// 全部图文小节连续阅读,唯一底部按钮展示 20 秒倒计时。
@MainActor
final class TrainingCourseViewController: TrainingBaseViewController {
private let service: any TrainingServing
private let viewModel: TrainingReadingViewModel
private let webView: WKWebView
private let bottomStack = UIStackView()
private let noticeLabel = TrainingUI.label(style: .footnote, color: AppColor.textSecondary)
private let actionButton = TrainingUI.button("正在加载课程…")
/// 当前课程标识,用于成绩页返回已有学习页面。
var taskID: String { viewModel.taskID }
private var readingTimer: Timer?
private var contentIsReady = false
private var contentLoadFailed = false
private var pageIsVisible = false
private var readingClock = TrainingReadingClock()
/// 开启当前任务的连续阅读页面,禁用课程 HTML 中的 JavaScript。
init(taskID: String, service: any TrainingServing) {
self.service = service
viewModel = TrainingReadingViewModel(taskID: taskID)
let configuration = WKWebViewConfiguration()
configuration.defaultWebpagePreferences.allowsContentJavaScript = false
webView = WKWebView(frame: .zero, configuration: configuration)
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func setupNavigationBar() { TrainingUI.navigation(self, title: "课程学习") }
override func setupUI() {
webView.navigationDelegate = self
view.backgroundColor = TrainingUI.background
webView.backgroundColor = TrainingUI.background
webView.isOpaque = false
bottomStack.axis = .vertical
bottomStack.spacing = 8
bottomStack.layoutMargins = UIEdgeInsets(top: 10, left: 12, bottom: 10, right: 12)
bottomStack.isLayoutMarginsRelativeArrangement = true
bottomStack.backgroundColor = AppColor.cardBackground
bottomStack.addArrangedSubview(noticeLabel)
bottomStack.addArrangedSubview(actionButton)
actionButton.accessibilityIdentifier = "training.reading.action"
view.addSubview(webView)
view.addSubview(bottomStack)
}
override func setupConstraints() {
webView.snp.makeConstraints {
$0.top.leading.trailing.equalTo(view.safeAreaLayoutGuide)
$0.bottom.equalTo(bottomStack.snp.top)
}
bottomStack.snp.makeConstraints { $0.leading.trailing.bottom.equalTo(view.safeAreaLayoutGuide) }
}
override func bindActions() {
actionButton.addTarget(self, action: #selector(actionTapped), for: .touchUpInside)
NotificationCenter.default.addObserver(self, selector: #selector(pauseReading), name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(resumeReading), name: UIApplication.didBecomeActiveNotification, object: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
pageIsVisible = true
loadCourse()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
pageIsVisible = false
pauseReading()
}
override func onSessionDidExpire() {
pauseReading()
navigationController?.popToRootViewController(animated: true)
}
private func loadCourse() {
pauseReading()
contentIsReady = false
contentLoadFailed = false
actionButton.isEnabled = false
Task { @MainActor in
await viewModel.load(service: service)
if let task = viewModel.task {
let sections = task.course.sections.map { "<section><h2>\(escape($0.title))</h2>\($0.contentHTML)</section>" }.joined()
let attachments = task.course.attachments.map { attachment in
guard let url = attachment.url, url.scheme?.lowercased() == "https", url.host != nil else {
return "<p>附件:\(escape(attachment.name))(尚未同步)</p>"
}
return "<p><a href=\"\(escape(url.absoluteString))\">📄 \(escape(attachment.name))</a></p>"
}.joined()
let demo = service.isDemo ? "<p class='demo'>开发演示 · 记录仅保存在本机,未同步景区后台</p>" : ""
let meta = task.mode == .exam ? "学习 + 考试 · \(task.course.sections.count) 节 · \(task.questions.count) 题 · \(task.passScore) 分及格" : "仅学习 · \(task.course.sections.count) 节"
webView.loadHTMLString("""
<!doctype html><html lang="zh-CN"><head><meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src https: data:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'">
<style>
*{box-sizing:border-box}body{font:15px -apple-system,BlinkMacSystemFont,sans-serif;color:#34435b;background:#f5f8fc;margin:0;padding:14px 13px;line-height:1.95;overflow-wrap:anywhere}
h1{font-size:17px;font-weight:600;line-height:1.6;color:#172033;margin:14px 0 6px}h2{font-size:15.5px;font-weight:600;color:#172033;margin:0 0 10px}img{max-width:100%;height:auto}table{max-width:100%;display:block;overflow:auto}section{margin:0 0 24px}section:last-child{margin-bottom:0}a{color:#2379ff}
.demo{color:#946116;background:#fff5e5;font-size:11px;padding:8px 10px;border-radius:6px;line-height:1.6;margin:0 0 12px}
.step{display:flex;gap:20px;background:#edf1f7;padding:9px 12px;border-radius:8px;font-size:13px;color:#8994a6}.step b{font-weight:500;color:#2379ff}
.muted{font-size:12.5px;color:#8491a6;line-height:1.65;margin:6px 0}.reading{background:white;border:1px solid #e3ebf5;border-radius:11px;padding:14px;margin-top:14px}
</style></head>
<body>\(demo)<div class='step'><b>1 课程学习</b><span>\(task.mode == .exam ? "2 在线考试" : "完成学习")</span></div><h1>\(escape(task.title))</h1><p class='muted'>\(escape(task.course.title))</p><p class='muted'>\(meta)</p><p class='muted'>\(escape(task.course.introduction))</p><div class='reading'>\(sections)</div>\(attachments)</body></html>
""", baseURL: nil)
}
applyState()
}
}
private func escape(_ text: String) -> String {
text.replacingOccurrences(of: "&", with: "&amp;").replacingOccurrences(of: "<", with: "&lt;")
.replacingOccurrences(of: ">", with: "&gt;").replacingOccurrences(of: "\"", with: "&quot;")
}
private func applyState() {
if let error = viewModel.errorMessage ?? (contentLoadFailed ? "课程加载失败,请重试" : nil) {
pauseReading()
noticeLabel.text = error
setActionTitle("重新加载")
actionButton.isEnabled = true
return
}
guard let task = viewModel.task else { return }
if let reason = task.submissionBlockReason(now: Date()) {
pauseReading()
noticeLabel.text = reason
setActionTitle("返回培训中心")
actionButton.isEnabled = true
} else if task.hasFinishedReading {
pauseReading()
noticeLabel.text = "课程阅读已完成"
setActionTitle(task.mode == .exam ? "开始考试" : "完成学习")
actionButton.isEnabled = true
} else {
noticeLabel.text = "请阅读课程内容,倒计时结束后" + (task.mode == .exam ? "即可考试" : "完成学习")
setActionTitle("\(task.mode == .exam ? "开始考试" : "完成学习")(\(viewModel.remainingSeconds)s)")
actionButton.isEnabled = false
}
}
private func setActionTitle(_ title: String) { var configuration = actionButton.configuration; configuration?.title = title; actionButton.configuration = configuration }
@objc private func pauseReading() {
readingTimer?.invalidate()
readingTimer = nil
readingClock.pause()
}
@objc private func resumeReading() {
guard pageIsVisible, contentIsReady, presentedViewController == nil,
navigationController?.topViewController === self, UIApplication.shared.applicationState == .active,
readingTimer == nil, viewModel.errorMessage == nil, let task = viewModel.task,
!task.hasFinishedReading, task.submissionBlockReason(now: Date()) == nil else { return }
readingClock.resume(at: ProcessInfo.processInfo.systemUptime)
let timer = Timer(timeInterval: 0.25, repeats: true) { [weak self] _ in
Task { @MainActor in await self?.recordSecond() }
}
readingTimer = timer
RunLoop.main.add(timer, forMode: .common)
}
private func recordSecond() async {
guard pageIsVisible, contentIsReady, presentedViewController == nil,
navigationController?.topViewController === self, readingTimer != nil,
UIApplication.shared.applicationState == .active, !viewModel.isBusy else { return }
let uptime = ProcessInfo.processInfo.systemUptime
guard readingClock.takeSecond(at: uptime) else { return }
await viewModel.recordSecond(service: service)
applyState()
}
@objc private func actionTapped() {
if viewModel.errorMessage != nil || contentLoadFailed { loadCourse(); return }
guard let task = viewModel.task else { return }
if task.submissionBlockReason(now: Date()) != nil || task.mode == .study && task.hasFinishedReading {
if let center = navigationController?.viewControllers.last(where: { $0 is TrainingCenterViewController }) {
navigationController?.popToViewController(center, animated: true)
}
} else if task.hasFinishedReading, task.mode == .exam {
navigationController?.pushViewController(TrainingExamViewController(taskID: task.id, service: service), animated: true)
}
}
}
extension TrainingCourseViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
contentIsReady = true
contentLoadFailed = false
applyState()
resumeReading()
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
contentIsReady = false
contentLoadFailed = true
pauseReading()
applyState()
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
contentIsReady = false
contentLoadFailed = true
pauseReading()
applyState()
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == .other, navigationAction.request.url?.absoluteString == "about:blank" {
decisionHandler(.allow)
return
}
decisionHandler(.cancel)
guard navigationAction.navigationType == .linkActivated,
let url = navigationAction.request.url, url.scheme?.lowercased() == "https", url.host != nil else { return }
pauseReading()
let controller = SFSafariViewController(url: url)
controller.delegate = self
present(controller, animated: true)
}
}
extension TrainingCourseViewController: SFSafariViewControllerDelegate {
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
controller.dismiss(animated: true) { [weak self] in self?.resumeReading() }
}
}
@@ -0,0 +1,276 @@
import SnapKit
import UIKit
/// 原生单选/多选答题页,支持逐题跳转、草稿恢复与确认交卷。
@MainActor
final class TrainingExamViewController: TrainingBaseViewController {
private let service: any TrainingServing
private let viewModel: TrainingExamViewModel
private let resetDraft: Bool
private let scrollView = UIScrollView()
private let contentStack = TrainingUI.card()
private let positionLabel = TrainingUI.label(style: .subheadline, color: AppColor.primary)
private let questionLabel = TrainingUI.label(style: .title3)
private let hintLabel = TrainingUI.label(style: .footnote, color: AppColor.textSecondary)
private let optionStack = UIStackView()
private let navigationStack = UIStackView()
private let previousButton = AppButton(title: "上一题", style: .secondary)
private let nextButton = AppButton(title: "下一题", style: .secondary)
private let bottomStack = UIStackView()
private let statusLabel = TrainingUI.label(style: .footnote, color: AppColor.textSecondary)
private let submitButton = AppButton(title: "交卷")
/// 重考时清除旧草稿,普通进入时恢复本人已保存的答案。
init(taskID: String, service: any TrainingServing, resetDraft: Bool = false) {
self.service = service
viewModel = TrainingExamViewModel(taskID: taskID)
self.resetDraft = resetDraft
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func setupNavigationBar() {
title = "培训答题"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "答题卡", style: .plain, target: self, action: #selector(answerCardTapped))
}
override func setupUI() {
scrollView.alwaysBounceVertical = true
optionStack.axis = .vertical
optionStack.spacing = 12
navigationStack.axis = .horizontal
navigationStack.spacing = 12
navigationStack.distribution = .fillEqually
navigationStack.addArrangedSubview(previousButton)
navigationStack.addArrangedSubview(nextButton)
if service.isDemo { contentStack.addArrangedSubview(TrainingUI.demoNotice()) }
[positionLabel, questionLabel, hintLabel, optionStack, navigationStack].forEach(contentStack.addArrangedSubview)
bottomStack.axis = .vertical
bottomStack.spacing = 8
bottomStack.backgroundColor = AppColor.cardBackground
bottomStack.layoutMargins = UIEdgeInsets(top: 12, left: 20, bottom: 12, right: 20)
bottomStack.isLayoutMarginsRelativeArrangement = true
bottomStack.addArrangedSubview(statusLabel)
bottomStack.addArrangedSubview(submitButton)
submitButton.accessibilityIdentifier = "training.exam.submit"
scrollView.addSubview(contentStack)
view.addSubview(scrollView)
view.addSubview(bottomStack)
applyState()
}
override func setupConstraints() {
scrollView.snp.makeConstraints {
$0.top.leading.trailing.equalTo(view.safeAreaLayoutGuide)
$0.bottom.equalTo(bottomStack.snp.top)
}
contentStack.snp.makeConstraints {
$0.edges.equalTo(scrollView.contentLayoutGuide).inset(16)
$0.width.equalTo(scrollView.frameLayoutGuide).offset(-32)
}
bottomStack.snp.makeConstraints { $0.leading.trailing.bottom.equalTo(view.safeAreaLayoutGuide) }
}
override func bindActions() {
previousButton.addTarget(self, action: #selector(previousTapped), for: .touchUpInside)
nextButton.addTarget(self, action: #selector(nextTapped), for: .touchUpInside)
submitButton.addTarget(self, action: #selector(submitTapped), for: .touchUpInside)
}
override func viewDidLoad() {
super.viewDidLoad()
loadExam()
}
override func onSessionDidExpire() { navigationController?.popToRootViewController(animated: true) }
private func loadExam() {
submitButton.isEnabled = false
Task { @MainActor in
await viewModel.load(service: service, resetDraft: resetDraft)
applyState()
}
}
private func applyState() {
for child in optionStack.arrangedSubviews { optionStack.removeArrangedSubview(child); child.removeFromSuperview() }
guard let task = viewModel.task, let question = viewModel.currentQuestion else {
positionLabel.text = ""
questionLabel.text = viewModel.errorMessage ?? "正在加载试卷…"
hintLabel.text = ""
navigationStack.isHidden = true
submitButton.setTitle("重新加载", for: .normal)
submitButton.isEnabled = viewModel.errorMessage != nil
navigationItem.rightBarButtonItem?.isEnabled = false
return
}
navigationStack.isHidden = false
navigationItem.rightBarButtonItem?.isEnabled = !viewModel.isBusy
positionLabel.text = "第 \(viewModel.currentIndex + 1) / \(task.questions.count) 题 · \(question.type == .single ? "单选题" : "多选题")"
questionLabel.text = question.stem
hintLabel.text = question.type == .single ? "请选择一个答案" : "请选择所有正确答案,少选、多选、错选均不得分"
for (index, option) in question.options.enumerated() {
let selected = viewModel.answers[question.id]?.contains(option.id) == true
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.isBusy
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) }
}
previousButton.isEnabled = !viewModel.isBusy && viewModel.currentIndex > 0
nextButton.isEnabled = !viewModel.isBusy && viewModel.currentIndex < task.questions.count - 1
statusLabel.text = viewModel.errorMessage ?? "已答 \(viewModel.answeredCount)/\(task.questions.count) · 答案已保存,可稍后继续"
statusLabel.textColor = viewModel.errorMessage == nil ? AppColor.textSecondary : AppColor.danger
submitButton.setTitle(viewModel.isBusy ? "正在保存…" : "交卷", for: .normal)
submitButton.isEnabled = !viewModel.isBusy
}
private func selectOption(_ id: String) {
Task { @MainActor in
let operation = Task { await viewModel.select(optionID: id, service: service) }
await Task.yield()
applyState()
await operation.value
applyState()
}
}
private func goToQuestion(_ index: Int) {
viewModel.goToQuestion(index)
applyState()
scrollView.setContentOffset(.zero, animated: false)
UIAccessibility.post(notification: .screenChanged, argument: questionLabel)
}
@objc private func previousTapped() { goToQuestion(viewModel.currentIndex - 1) }
@objc private func nextTapped() { goToQuestion(viewModel.currentIndex + 1) }
@objc private func answerCardTapped() {
guard let task = viewModel.task, !viewModel.isBusy else { return }
let controller = TrainingAnswerCardViewController(task: task, answers: viewModel.answers, currentIndex: viewModel.currentIndex)
controller.onSelect = { [weak self] index in self?.goToQuestion(index) }
let navigation = UINavigationController(rootViewController: controller)
if let sheet = navigation.sheetPresentationController { sheet.detents = [.medium(), .large()]; sheet.prefersGrabberVisible = true }
present(navigation, animated: true)
}
@objc private func submitTapped() {
guard !viewModel.isBusy else { return }
guard let task = viewModel.task else { loadExam(); return }
if let missing = viewModel.firstUnansweredIndex {
goToQuestion(missing)
showToast("还有 \(task.questions.count - viewModel.answeredCount) 道题未作答,已定位到第一道")
return
}
let alert = UIAlertController(title: "确认交卷?", message: "已完成 \(task.questions.count) 道题,提交后将生成本次考试记录。", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "继续检查", style: .cancel))
alert.addAction(UIAlertAction(title: "交卷", style: .default) { [weak self] _ in self?.performSubmit() })
present(alert, animated: true)
}
private func performSubmit() {
Task { @MainActor in
let operation = Task { await viewModel.submit(service: service) }
await Task.yield()
applyState()
let attempt = await operation.value
applyState()
guard let attempt, let navigationController else { return }
let result = TrainingResultViewController(taskID: viewModel.taskID, attemptID: attempt.id, service: service)
navigationController.setViewControllers(Array(navigationController.viewControllers.dropLast()) + [result], animated: true)
}
}
}
/// 可滚动的网格答题卡,支持最多 500 道题。
@MainActor
final class TrainingAnswerCardViewController: UIViewController {
private let task: TrainingTask
private let answers: TrainingAnswers
private let currentIndex: Int
private let collectionView: UICollectionView
private var dataSource: UICollectionViewDiffableDataSource<Int, Int>!
var onSelect: ((Int) -> Void)?
/// 根据本次草稿展示已答和当前题,不显示正确答案。
init(task: TrainingTask, answers: TrainingAnswers, currentIndex: Int) {
self.task = task
self.answers = answers
self.currentIndex = currentIndex
let layout = UICollectionViewFlowLayout()
layout.minimumInteritemSpacing = 12
layout.minimumLineSpacing = 12
layout.sectionInset = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func viewDidLoad() {
super.viewDidLoad()
title = "答题卡 · 蓝色为已答"
navigationItem.rightBarButtonItem = UIBarButtonItem(systemItem: .done, primaryAction: UIAction { [weak self] _ in self?.dismiss(animated: true) })
collectionView.backgroundColor = AppColor.pageBackgroundSoft
collectionView.delegate = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "question")
view.addSubview(collectionView)
collectionView.snp.makeConstraints { $0.edges.equalTo(view.safeAreaLayoutGuide) }
dataSource = UICollectionViewDiffableDataSource<Int, Int>(collectionView: collectionView) { [weak self] collection, indexPath, index in
guard let self else { return nil }
let cell = collection.dequeueReusableCell(withReuseIdentifier: "question", for: indexPath)
let answered = !(self.answers[self.task.questions[index].id] ?? []).isEmpty
var content = UIListContentConfiguration.cell()
content.text = "\(index + 1)"
content.textProperties.alignment = .center
content.textProperties.color = answered ? AppColor.primary : AppColor.textSecondary
content.directionalLayoutMargins = .zero
cell.contentConfiguration = content
cell.backgroundColor = answered ? AppColor.primaryLight : AppColor.cardBackground
cell.layer.cornerRadius = 10
cell.layer.borderWidth = index == self.currentIndex ? 2 : 0
cell.layer.borderColor = AppColor.primary.cgColor
cell.isAccessibilityElement = true
cell.accessibilityLabel = "第 \(index + 1) 题,\(answered ? "已答" : "未答")\(index == self.currentIndex ? ",当前题" : "")"
cell.accessibilityTraits = .button
return cell
}
var snapshot = NSDiffableDataSourceSnapshot<Int, Int>()
snapshot.appendSections([0])
snapshot.appendItems(Array(task.questions.indices))
dataSource.apply(snapshot, animatingDifferences: false)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.itemSize = CGSize(width: floor((collectionView.bounds.width - 88) / 5), height: 52)
}
}
}
extension TrainingAnswerCardViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let index = dataSource.itemIdentifier(for: indexPath) else { return }
let selection = onSelect
dismiss(animated: true) { selection?(index) }
}
}
@@ -0,0 +1,188 @@
import SnapKit
import UIKit
/// 成绩概览、可展开解析和返回学习入口,历史记录只按最新任务状态提供重考。
@MainActor
final class TrainingResultViewController: TrainingBaseViewController {
private let taskID: String
private let attemptID: String
private let service: any TrainingServing
private var loadedTask: TrainingTask?
private var loadedAttempt: TrainingAttempt?
private var loadFailed = false
private var showsDetails = false
private let scrollView = UIScrollView()
private let contentStack = UIStackView()
private let footer = UIView()
private let actionButton = TrainingUI.button("完成,返回培训中心")
/// 使用记录 ID 读取最新本人任务,禁止通过后从旧失败记录继续重考。
init(taskID: String, attemptID: String, service: any TrainingServing) {
self.taskID = taskID
self.attemptID = attemptID
self.service = service
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func setupNavigationBar() { TrainingUI.navigation(self, title: "考试结果") }
override func setupUI() {
view.backgroundColor = TrainingUI.background
contentStack.axis = .vertical
contentStack.spacing = 12
scrollView.addSubview(contentStack)
view.addSubview(scrollView)
footer.backgroundColor = .white
let line = UIView()
line.backgroundColor = TrainingUI.border
footer.addSubview(line)
line.snp.makeConstraints { $0.leading.trailing.top.equalToSuperview(); $0.height.equalTo(1) }
footer.addSubview(actionButton)
view.addSubview(footer)
actionButton.accessibilityIdentifier = "training.result.action"
}
override func setupConstraints() {
footer.snp.makeConstraints { $0.leading.trailing.bottom.equalToSuperview() }
actionButton.snp.makeConstraints {
$0.leading.trailing.equalToSuperview().inset(12)
$0.top.equalToSuperview().offset(10)
$0.bottom.equalTo(view.safeAreaLayoutGuide).offset(-10)
}
scrollView.snp.makeConstraints { $0.top.leading.trailing.equalTo(view.safeAreaLayoutGuide); $0.bottom.equalTo(footer.snp.top) }
contentStack.snp.makeConstraints {
$0.edges.equalTo(scrollView.contentLayoutGuide).inset(UIEdgeInsets(top: 14, left: 13, bottom: 20, right: 13))
$0.width.equalTo(scrollView.frameLayoutGuide).offset(-26)
}
}
override func bindActions() { actionButton.addTarget(self, action: #selector(actionTapped), for: .touchUpInside) }
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated); loadResult() }
override func onSessionDidExpire() { navigationController?.popToRootViewController(animated: true) }
private func loadResult() { Task { @MainActor in await reload() } }
/// 页面出现时重新读取记录,失败可重试,不展示上个任务成绩。
func reload() async {
actionButton.isEnabled = false
do {
let task = try await service.task(id: taskID)
guard let attempt = task.progress.attempts.first(where: { $0.id == attemptID }) else { throw TrainingError.notFound }
loadedTask = task
loadedAttempt = attempt
loadFailed = false
render(task: task, attempt: attempt)
} catch {
loadedTask = nil
loadedAttempt = nil
loadFailed = true
clearContent()
contentStack.addArrangedSubview(TrainingUI.text(error.localizedDescription, color: TrainingUI.muted))
setActionTitle("重新加载")
}
actionButton.isEnabled = true
}
private func clearContent() {
for child in contentStack.arrangedSubviews { contentStack.removeArrangedSubview(child); child.removeFromSuperview() }
}
private func setActionTitle(_ title: String) { var configuration = actionButton.configuration; configuration?.title = title; actionButton.configuration = configuration }
private func render(task: TrainingTask, attempt: TrainingAttempt) {
clearContent()
if attempt.isDemo { contentStack.addArrangedSubview(TrainingUI.demoNotice()) }
let summary = UIStackView()
summary.axis = .vertical
summary.spacing = 11
summary.alignment = .center
summary.backgroundColor = .white
summary.layer.cornerRadius = 11
summary.layer.borderWidth = 1
summary.layer.borderColor = TrainingUI.border.cgColor
summary.isLayoutMarginsRelativeArrangement = true
summary.layoutMargins = UIEdgeInsets(top: 25, left: 12, bottom: 25, right: 12)
let symbol = UIImageView(image: UIImage(systemName: attempt.passed ? "checkmark.circle.fill" : "info.circle.fill"))
symbol.tintColor = attempt.passed ? TrainingUI.success : UIColor(red: 237/255, green: 140/255, blue: 36/255, alpha: 1)
symbol.contentMode = .scaleAspectFit
symbol.snp.makeConstraints { $0.size.equalTo(54) }
summary.addArrangedSubview(symbol)
let title = TrainingUI.text(attempt.passed ? "考试通过,学习任务已完成" : "本次未通过,再接再厉", size: 16.5, weight: .bold)
title.textAlignment = .center
summary.addArrangedSubview(title)
let score = UIStackView(arrangedSubviews: [TrainingUI.text(attempt.scoreText, size: 46, weight: .bold, color: TrainingUI.primary), TrainingUI.text("/ 100 分", size: 13, color: TrainingUI.muted)])
score.alignment = .firstBaseline
score.spacing = 6
score.snp.makeConstraints { $0.height.greaterThanOrEqualTo(69) }
summary.addArrangedSubview(score)
let detail = TrainingUI.text("\(task.passScore) 分及格 · \(TrainingUI.date(attempt.submittedAt))", size: 12.5, color: TrainingUI.muted)
detail.textAlignment = .center
summary.addArrangedSubview(detail)
contentStack.addArrangedSubview(summary)
let counts = TrainingUI.card()
let row = UIStackView(arrangedSubviews: [TrainingUI.text("答对 \(attempt.correctCount) 题"), TrainingUI.text("答错 \(attempt.questionCount - attempt.correctCount) 题")])
row.distribution = .fillEqually
for label in row.arrangedSubviews.compactMap({ $0 as? UILabel }) { label.textAlignment = .center }
counts.addArrangedSubview(row)
contentStack.addArrangedSubview(counts)
let details = TrainingUI.button(showsDetails ? "收起答案解析" : "查看答案解析", secondary: true)
details.accessibilityIdentifier = "training.result.details"
details.addTarget(self, action: #selector(toggleDetails), for: .touchUpInside)
contentStack.addArrangedSubview(details)
let learning = TrainingUI.button("返回学习", plain: true)
learning.accessibilityIdentifier = "training.result.learning"
learning.addTarget(self, action: #selector(returnToLearning), for: .touchUpInside)
contentStack.addArrangedSubview(learning)
if showsDetails {
for (index, review) in attempt.reviews.enumerated() {
let card = TrainingUI.card()
let top = UIStackView(arrangedSubviews: [TrainingUI.text("第 \(index + 1) 题", size: 12.5, color: TrainingUI.muted), TrainingUI.text(review.isCorrect ? "回答正确" : "回答错误", size: 12, color: review.isCorrect ? TrainingUI.success : .systemRed)])
top.distribution = .equalSpacing
card.addArrangedSubview(top)
card.addArrangedSubview(TrainingUI.text(review.question.stem, size: 15.5, weight: .semibold))
for (optionIndex, option) in review.question.options.enumerated() {
card.addArrangedSubview(TrainingUI.text("\(TrainingQuestion.optionLetter(optionIndex)). \(option.text)", size: 13.5, color: UIColor(red: 92/255, green: 108/255, blue: 132/255, alpha: 1)))
}
func letters(_ ids: Set<String>) -> String {
let values = review.question.options.enumerated().compactMap { ids.contains($0.element.id) ? TrainingQuestion.optionLetter($0.offset) : nil }
return values.isEmpty ? "未作答" : values.joined(separator: "、")
}
card.addArrangedSubview(TrainingUI.text("你的答案:\(letters(review.selectedIDs)) · 正确答案:\(letters(review.correctIDs))", size: 12.5, color: TrainingUI.muted))
card.addArrangedSubview(TrainingUI.notice(review.explanation.isEmpty ? "暂无解析" : review.explanation))
contentStack.addArrangedSubview(card)
}
}
let canRetry = !attempt.passed && task.submissionBlockReason(now: Date()) == nil
contentStack.addArrangedSubview(TrainingUI.text(canRetry ? "截止前可不限次数重考,每次成绩都会保留。" : "本次记录只读,可回顾课程内容和答案解析。", size: 12, color: TrainingUI.muted))
setActionTitle(canRetry ? "再考一次" : "完成,返回培训中心")
}
@objc private func toggleDetails() {
guard let task = loadedTask, let attempt = loadedAttempt else { return }
showsDetails.toggle()
render(task: task, attempt: attempt)
}
/// 无论是否通过都能返回本次课程,优先复用导航栈中的课程页面。
@objc private func returnToLearning() {
guard loadedTask != nil, let navigationController else { return }
if let course = navigationController.viewControllers.last(where: { ($0 as? TrainingCourseViewController)?.taskID == taskID }) {
navigationController.popToViewController(course, animated: true)
} else {
navigationController.pushViewController(TrainingCourseViewController(taskID: taskID, service: service), animated: true)
}
}
@objc private func actionTapped() {
if loadFailed { loadResult(); return }
guard let task = loadedTask, let attempt = loadedAttempt, let navigationController else { return }
if !attempt.passed, task.submissionBlockReason(now: Date()) == nil {
navigationController.setViewControllers(Array(navigationController.viewControllers.dropLast()) + [TrainingExamViewController(taskID: taskID, service: service, resetDraft: true)], animated: true)
} else if let center = navigationController.viewControllers.last(where: { $0 is TrainingCenterViewController }) {
navigationController.popToViewController(center, animated: true)
} else { navigationController.setViewControllers([TrainingCenterViewController(service: service)], animated: true) }
}
}
+261
View File
@@ -0,0 +1,261 @@
import SnapKit
import UIKit
/// 与小程序培训页面一致的色彩、字体和内容间距。
@MainActor
enum TrainingUI {
static let primary = UIColor(red: 35/255, green: 121/255, blue: 1, alpha: 1)
static let background = UIColor(red: 245/255, green: 248/255, blue: 252/255, alpha: 1)
static let textColor = UIColor(red: 23/255, green: 32/255, blue: 51/255, alpha: 1)
static let muted = UIColor(red: 132/255, green: 145/255, blue: 166/255, alpha: 1)
static let border = UIColor(red: 227/255, green: 235/255, blue: 245/255, alpha: 1)
static let hintColor = UIColor(red: 189/255, green: 121/255, blue: 24/255, alpha: 1)
static let hintBackground = UIColor(red: 1, green: 246/255, blue: 233/255, alpha: 1)
static let success = UIColor(red: 21/255, green: 151/255, blue: 108/255, alpha: 1)
/// 创建支持系统字体缩放的标签。
static func text(_ value: String = "", size: CGFloat = 14, weight: UIFont.Weight = .regular, color: UIColor = textColor) -> UILabel {
let label = UILabel()
label.text = value
label.font = UIFontMetrics(forTextStyle: .body).scaledFont(for: .systemFont(ofSize: size, weight: weight))
label.adjustsFontForContentSizeCategory = true
label.textColor = color
label.numberOfLines = 0
return label
}
/// 为答题等现有页面保留语义字体入口。
static func label(_ text: String = "", style: UIFont.TextStyle = .body, color: UIColor = textColor) -> UILabel {
let label = self.text(text, color: color)
label.font = .preferredFont(forTextStyle: style)
return label
}
/// 白色内容卡片使用细边框和统一内边距。
static func card() -> UIStackView {
let stack = UIStackView()
stack.axis = .vertical
stack.spacing = 10
stack.backgroundColor = .white
stack.layer.cornerRadius = 11
stack.layer.borderWidth = 1
stack.layer.borderColor = border.cgColor
stack.layoutMargins = UIEdgeInsets(top: 14, left: 14, bottom: 14, right: 14)
stack.isLayoutMarginsRelativeArrangement = true
return stack
}
/// 提示内容在浅橙背景中展示。
static func notice(_ value: String, demo: Bool = false) -> UIStackView {
let box = UIStackView(arrangedSubviews: [text(value, size: demo ? 11 : 12, color: hintColor)])
box.axis = .vertical
box.backgroundColor = hintBackground
box.layer.cornerRadius = 6
box.isLayoutMarginsRelativeArrangement = true
box.layoutMargins = UIEdgeInsets(top: 9, left: 10, bottom: 9, right: 10)
return box
}
/// 明确标识本机演示边界。
static func demoNotice() -> UIStackView {
notice("开发演示 · 记录仅保存在本机,未同步景区后台", demo: true)
}
/// 使用本地时区展示任务截止和考试时间。
static func date(_ date: Date) -> String {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "zh_CN")
formatter.dateFormat = "MM-dd HH:mm"
return formatter.string(from: date)
}
/// 培训专用按钮,文字缩放时高度随内容增加。
static func button(_ title: String, secondary: Bool = false, plain: Bool = false, pill: Bool = false) -> UIButton {
let button = UIButton(type: .system)
var configuration = UIButton.Configuration.plain()
configuration.title = title
configuration.baseForegroundColor = plain || secondary ? primary : .white
configuration.background.backgroundColor = plain ? .clear : secondary ? primary.withAlphaComponent(0.08) : primary
configuration.background.cornerRadius = pill ? 24 : 11
configuration.contentInsets = NSDirectionalEdgeInsets(top: plain ? 10 : 12, leading: 14, bottom: plain ? 10 : 12, trailing: 14)
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
var output = incoming
output.font = UIFontMetrics(forTextStyle: .body).scaledFont(for: .systemFont(ofSize: 14, weight: plain ? .regular : .semibold))
return output
}
button.configuration = configuration
if !plain, !secondary {
button.configurationUpdateHandler = { button in
var updated = button.configuration
updated?.background.backgroundColor = button.isEnabled ? primary : border
updated?.baseForegroundColor = button.isEnabled ? .white : muted
button.configuration = updated
}
}
button.titleLabel?.adjustsFontForContentSizeCategory = true
button.snp.makeConstraints { $0.height.greaterThanOrEqualTo(44) }
return button
}
/// 导航栏保持普通白色背景,入口使用文本与箭头。
static func navigation(_ controller: UIViewController, title: String) {
controller.title = title
let appearance = UINavigationBarAppearance()
appearance.configureWithOpaqueBackground()
appearance.backgroundColor = .white
appearance.shadowColor = .clear
appearance.titleTextAttributes = [.font: UIFont.systemFont(ofSize: 17, weight: .medium), .foregroundColor: textColor]
controller.navigationItem.standardAppearance = appearance
controller.navigationItem.scrollEdgeAppearance = appearance
controller.navigationItem.compactAppearance = appearance
controller.navigationItem.backButtonDisplayMode = .minimal
let back = UIButton(type: .system)
back.tintColor = textColor
back.setImage(UIImage(systemName: "chevron.left", withConfiguration: UIImage.SymbolConfiguration(pointSize: 20, weight: .medium)), for: .normal)
back.accessibilityLabel = "返回"
back.snp.makeConstraints { $0.size.equalTo(44) }
back.addAction(UIAction { [weak controller] _ in controller?.navigationController?.popViewController(animated: true) }, for: .touchUpInside)
let item = UIBarButtonItem(customView: back)
if #available(iOS 26.0, *) { item.hidesSharedBackground = true }
controller.navigationItem.leftBarButtonItem = item
}
}
/// 任务卡显示截止、课程小节、提示、进度条和对应的操作入口。
@MainActor
final class TrainingTaskCell: UITableViewCell {
static let reuseIdentifier = "TrainingTaskCell"
private let stack = TrainingUI.card()
private let deadlineLabel = TrainingUI.text(size: 11.5, color: .systemRed)
private let statusLabel = TrainingUI.text(size: 11, color: TrainingUI.primary)
private let titleLabel = TrainingUI.text(size: 15.5, weight: .semibold)
private let publisherLabel = TrainingUI.text(size: 12.5, color: TrainingUI.muted)
private let metaLabel = TrainingUI.text(size: 12.5, color: TrainingUI.muted)
private let hintLabel = TrainingUI.text(size: 12, color: TrainingUI.hintColor)
private let progressView = UIProgressView(progressViewStyle: .bar)
private let progressLabel = TrainingUI.text(size: 12.5, color: TrainingUI.muted)
private let actionButton = TrainingUI.button("去学习", pill: true)
private let footer = UIStackView()
var onAction: (() -> Void)?
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = .clear
selectionStyle = .none
contentView.addSubview(stack)
let deadline = UIStackView(arrangedSubviews: [deadlineLabel])
deadline.backgroundColor = UIColor.systemRed.withAlphaComponent(0.06)
deadline.layer.cornerRadius = 12
deadline.isLayoutMarginsRelativeArrangement = true
deadline.layoutMargins = UIEdgeInsets(top: 4, left: 8, bottom: 4, right: 8)
let top = UIStackView(arrangedSubviews: [deadline, UIView(), statusLabel])
top.alignment = .center
top.spacing = 8
statusLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
let hint = UIStackView(arrangedSubviews: [hintLabel])
hint.backgroundColor = TrainingUI.hintBackground
hint.layer.cornerRadius = 6
hint.isLayoutMarginsRelativeArrangement = true
hint.layoutMargins = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
progressView.progressTintColor = TrainingUI.primary
progressView.trackTintColor = TrainingUI.border
progressView.layer.cornerRadius = 3
progressView.clipsToBounds = true
progressView.snp.makeConstraints { $0.height.equalTo(6) }
footer.spacing = 12
footer.alignment = .center
footer.addArrangedSubview(progressLabel)
footer.addArrangedSubview(actionButton)
progressLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
actionButton.setContentHuggingPriority(.defaultHigh, for: .horizontal)
actionButton.setContentCompressionResistancePriority(.required, for: .horizontal)
actionButton.snp.makeConstraints { $0.width.greaterThanOrEqualTo(140).priority(750) }
[top, titleLabel, publisherLabel, metaLabel, hint, progressView, footer].forEach(stack.addArrangedSubview)
stack.setCustomSpacing(14, after: top)
stack.setCustomSpacing(14, after: metaLabel)
stack.snp.makeConstraints { $0.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 13, bottom: 10, right: 13)) }
actionButton.addTarget(self, action: #selector(actionTapped), for: .touchUpInside)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 每个任务始终可回顾课程,只有已读完且有效时直接进入考试。
func configure(task: TrainingTask) {
let presentation = TrainingTaskPresentation(task: task)
titleLabel.text = task.title
deadlineLabel.text = "截止时间:\(TrainingUI.date(task.endAt))"
statusLabel.text = task.learnerStatus.title
statusLabel.textColor = task.learnerStatus == .completed ? TrainingUI.success : TrainingUI.primary
publisherLabel.text = "发布人:\(task.publisherText)"
metaLabel.text = task.mode == .exam ? "学习 + 考试 · \(task.course.sections.count) 节 · \(task.questions.count) 题 · \(task.passScore) 分及格" : "仅学习 · \(task.course.sections.count) 节"
hintLabel.text = presentation.hint
progressView.progress = Float(presentation.progressPercent) / 100
progressLabel.text = "学习进度 \(presentation.progressPercent)%"
var configuration = actionButton.configuration
configuration?.title = presentation.actionTitle
actionButton.configuration = configuration
actionButton.accessibilityIdentifier = "training.task.action.\(task.id)"
footer.axis = traitCollection.preferredContentSizeCategory.isAccessibilityCategory ? .vertical : .horizontal
}
@objc private func actionTapped() { onAction?() }
}
/// 考试记录沿用小程序的标题、蓝色得分和通过状态卡片。
@MainActor
final class TrainingRecordCell: UITableViewCell {
static let reuseIdentifier = "TrainingRecordCell"
private let stack = TrainingUI.card()
private let titleLabel = TrainingUI.text(weight: .semibold)
private let scoreLabel = TrainingUI.text(weight: .semibold, color: TrainingUI.primary)
private let detailLabel = TrainingUI.text(size: 11.5, color: TrainingUI.muted)
private let statusLabel = TrainingUI.text(size: 11.5)
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = .clear
selectionStyle = .none
let top = UIStackView(arrangedSubviews: [titleLabel, scoreLabel])
top.spacing = 12
top.alignment = .top
scoreLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
scoreLabel.setContentHuggingPriority(.required, for: .horizontal)
titleLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
let bottom = UIStackView(arrangedSubviews: [detailLabel, statusLabel])
bottom.spacing = 12
bottom.alignment = .top
statusLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
statusLabel.setContentHuggingPriority(.required, for: .horizontal)
detailLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
stack.addArrangedSubview(top)
stack.addArrangedSubview(bottom)
contentView.addSubview(stack)
stack.snp.makeConstraints { $0.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 13, bottom: 10, right: 13)) }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 展示已提交记录,点击后进入该次成绩。
func configure(task: TrainingTask, attempt: TrainingAttempt) {
titleLabel.text = task.title
scoreLabel.text = "\(attempt.scoreText) 分"
detailLabel.text = "\(TrainingUI.date(attempt.submittedAt)) · 答对 \(attempt.correctCount) / \(attempt.questionCount) 题"
statusLabel.text = attempt.passed ? "已通过" : "未通过"
statusLabel.textColor = attempt.passed ? TrainingUI.success : .systemRed
}
}
/// 培训页面在账号或景区切换时立即关闭,停止展示旧身份记录。
@MainActor
class TrainingBaseViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
for name in [NotificationName.accountDidSwitch, NotificationName.scenicDidChange] {
NotificationCenter.default.addObserver(self, selector: #selector(contextChanged), name: name, object: nil)
}
}
@objc private func contextChanged() { navigationController?.popToRootViewController(animated: false) }
}