You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI技术问询:从最后一个练习视图返回主页时隐藏返回按钮

解决SwiftUI返回主页后导航栏显示返回按钮的问题

问题根源

你当前使用NavigationLink跳转到ContentView,本质是把主页新增到导航栈的顶部,而非回到栈底的原始主页,因此导航栏会显示返回按钮(指向之前的训练视图)。

推荐解决方案(iOS16+ 原生SwiftUI方式)

使用NavigationStack的路径绑定来管理导航栈,重置路径即可直接回到根主页,且不会显示返回按钮。

步骤1:修改主页(ContentView)

用NavigationStack绑定路径数组,统一管理页面跳转:

import SwiftUI

struct ContentView: View {
    // 用数组存储导航路径,也可以定义枚举来更规范地标识页面
    @State private var navigationPath: [String] = []
    // 示例训练计划,替换成你实际的数据源
    let samplePlan = ExercisePlan(/* 你的训练计划参数 */)

    var body: some View {
        NavigationStack(path: $navigationPath) {
            // 主页内容,比如训练计划选择按钮
            VStack(spacing: 20) {
                Text("健身训练")
                    .font(.largeTitle)
                    .fontWeight(.bold)
                
                Button("开始训练计划") {
                    navigationPath.append("exercise1")
                }
                .padding()
                .background(.blue)
                .foregroundColor(.white)
                .cornerRadius(10)
            }
            // 配置导航目标页面
            .navigationDestination(for: String.self) { page in
                switch page {
                case "exercise1":
                    ExerciseScreen1View(plan: samplePlan, path: $navigationPath)
                case "exercise2":
                    ExerciseScreen2View(plan: samplePlan, path: $navigationPath)
                case "exercise3":
                    ExerciseScreen3View(plan: samplePlan, path: $navigationPath)
                case "exercise4":
                    ExerciseScreen4View(plan: samplePlan, path: $navigationPath)
                case "exercise5":
                    ExerciseScreen5View(exercisePlan: samplePlan, path: $navigationPath)
                default:
                    EmptyView()
                }
            }
            // 主页默认隐藏返回按钮(可选,确保初始状态无返回键)
            .navigationBarBackButtonHidden(true)
        }
    }
}

步骤2:修改最后一个训练视图(ExerciseScreen5View)

接收路径绑定,用按钮重置路径回到根主页:

import SwiftUI
import AVKit

struct ExerciseScreen5View: View {
    var countdownTimer = 300
    @State var player = AVPlayer()
    var exercisePlan: ExercisePlan
    // 接收导航路径的绑定
    @Binding var path: [String]

    var body: some View {
        VStack {
            Text(exercisePlan.exercise5.title)
                .font(.system(size: 35, weight: .medium))
            
            VideoPlayer(player: exercisePlan.exercise5.video)
                .scaledToFit()
                .cornerRadius(10)
            
            Text(exercisePlan.exercise5.steps)
                .font(.system(size: 20, weight: .regular))
                .padding()
            
            TimerView()
                .padding(.bottom, 35)
            
            // 替换原NavigationLink为普通按钮,重置路径回到根视图
            Button("返回主页") {
                path.removeAll()
            }
            .padding()
            .background(Color(red: 184/255, green: 243/255, blue: 255/255))
            .foregroundColor(.black)
            .cornerRadius(10)
        }
    }
}

struct ExerciseScreen5View_Previews: PreviewProvider {
    static var previews: some View {
        NavigationStack {
            ExerciseScreen5View(
                exercisePlan: ExercisePlan(
                    title: "Exercise Plan 1", 
                    details: "Choose this plan for a more basic workout",
                    exercise: Exercise(title: "Tricep Stretch", duration: 5, steps: "Lift your left elbow straight up while bending your arm. Grab your left elbow with your right hand and pull your left elbow towards your head or slightly behind your head with light pressure. (We recommend doing 10 seconds per rep)", video: AVPlayer(url:  Bundle.main.url(forResource: "TricepStretch" , withExtension: "MOV")!)),
                    exercise2: Exercise(title: "Toe Touches", duration: 5, steps: "Sit with your legs closed and toes pointing up. Keep your knees straight while stretching your arms forward to touch your toes. (We recommend doing 20 seconds per rep)", video: AVPlayer(url:  Bundle.main.url(forResource: "ToeTouches" , withExtension: "MOV")!)),
                    exercise3: Exercise(title: "Arm Circles", duration: 5, steps: "Hold your arms straight out to your sides, then swing them forwards or backwards in circles. Try to keep your shoulders down while doing this exercise. (We recommend doing 20 seconds per rep then changing sides)", video: AVPlayer(url:  Bundle.main.url(forResource: "ArmCircles" , withExtension: "MOV")!)),
                    exercise4: Exercise(title: "Elbow Stretch", duration: 5, steps: "Lift your left arm up while pushing it towards your chest, with your elbow pointing forward. (We recommend doing 10 seconds per rep)", video: AVPlayer(url:  Bundle.main.url(forResource: "ElbowStretch" , withExtension: "MOV")!)),
                    exercise5: Exercise(title: "Calf Raises", duration: 5, steps: "Raise your heels off the floor and return to the starting position, by slowly lowering your heels. (We recommend doing 20 seconds per rep)", video: AVPlayer(url:  Bundle.main.url(forResource: "CalfRaises" , withExtension: "MOV")!))
                ),
                path: .constant([])
            )
        }
    }
}

兼容iOS13-15的方案

如果需要兼容旧版本,可以通过UIKit的UINavigationController直接回到根视图:

// 在ExerciseScreen5View中替换原NavigationLink为以下按钮
Button("返回主页") {
    guard let window = UIApplication.shared.windows.first,
          let navController = window.rootViewController as? UINavigationController else {
        return
    }
    navController.popToRootViewController(animated: true)
}

内容的提问来源于stack exchange,提问作者Zudoturiku

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 11:10:41