SwiftUI如何给按钮和.sheet添加if else判断实现随机按钮跳转不同视图
SwiftUI 随机训练部位弹窗功能实现方案
问题原因
现有代码仅通过单一Bool类型状态控制弹窗,且弹窗内容硬编码固定为ArmExerciseView,和随机生成的训练部位没有关联,所以无论点击什么内容的按钮都只会弹出手臂训练视图;同时原workoutGen()方法每次调用都会重新生成随机值,存在按钮显示内容和点击后判断的部位不一致的隐患。
最简修复代码
struct ContentView: View { // 控制弹窗是否弹出 @State private var showWorkoutView: Bool = false // 存储启动时生成的当日固定训练部位 @State private var todayWorkout: String = "" let workouts = ["Arms", "Legs", "Back", "Core"] var body: some View { VStack { VStack { Text("Random workout for the day:") .bold() .font(.title) } Button(todayWorkout) { showWorkoutView = true } .font(.title2) .sheet(isPresented: $showWorkoutView, content: { // 通过switch分支匹配训练部位,返回对应视图 switch todayWorkout { case "Arms": ArmExerciseView() case "Legs": LegExerciseView() case "Back": BackExerciseView() case "Core": CoreExerciseView() default: EmptyView() } }) } .onAppear { // 启动时仅生成一次随机训练部位,避免重复随机导致数据不一致 todayWorkout = workouts.randomElement() ?? "Arms" } } }
注意:代码中的
LegExerciseView、BackExerciseView、CoreExerciseView请替换为你自己实现的对应部位的训练视图。
可选优化方案
如果需要更规范的状态管理,可使用sheet(item:)构造器实现,无需单独维护弹窗控制Bool变量:
struct ContentView: View { // 存储当前要展示的训练部位,nil表示不弹窗 @State private var selectedWorkout: String? @State private var todayWorkout: String = "" let workouts = ["Arms", "Legs", "Back", "Core"] var body: some View { VStack { VStack { Text("Random workout for the day:") .bold() .font(.title) } Button(todayWorkout) { selectedWorkout = todayWorkout } .font(.title2) .sheet(item: $selectedWorkout, content: { workout in switch workout { case "Arms": ArmExerciseView() case "Legs": LegExerciseView() case "Back": BackExerciseView() case "Core": CoreExerciseView() default: EmptyView() } }) } .onAppear { todayWorkout = workouts.randomElement() ?? "Arms" } } } // 扩展String遵守Identifiable协议,满足sheet(item:)的参数要求 extension String: Identifiable { public var id: String { self } }
内容的提问来源于stack exchange,提问作者hps28
相关产品推荐
相关产品推荐

