如何将 if else 语句添加到按钮和 .sheet?

时间:2021-07-17 05:33:26

标签: ios swift xcode swiftui

我是 SwiftUI 的新手,正在尝试创建一个简单的应用程序,每次应用程序启动时都会生成一个随机按钮。随机按钮生成一个链接到该随机按钮的新视图。当前,它链接到每次按下按钮时显示的一个视图。 这是我的代码:

struct ContentView: View {
@State private var armview: Bool = false
let workouts = ["Arms", "Legs", "Back", "Core"]

var body: some View {
    VStack {
        VStack {
            Text("Random workout for the day:")
                .bold()
                .font(.title)
        }
        Button(workoutGen()) {
            self.armview = true
        }
        .font(.title2)
        .sheet(isPresented: $armview, content: {
            ArmExerciseView()
        })
    }
}

func workoutGen() -> String {
    let workout = workouts.randomElement()
    return workout ?? "nil"
}}

我正在尝试找出如何附加 if-else 条件或切换案例,以便我可以根据出现和点击的按钮呈现不同的视图。 所以腿部、背部、核心等的不同视图。

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

import SwiftUI

@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

struct ContentView: View {
    @State private var armview: Bool = false
    let workouts = ["Arms", "Legs", "Back", "Core"]
    @State private var workoutSelection = "workout selection"
    
    var body: some View {
        VStack {
            VStack {
                Text("Random workout for the day:").bold().font(.title)
            }
            Button(workoutSelection) {
                armview = true
            }
            .font(.title2)
            .sheet(isPresented: $armview, onDismiss: {workoutGen()}) {
                switch workoutSelection {
                case "Arms": Text("Arms") // ArmExerciseView()
                case "Legs": Text("Legs")
                case "Back": Text("Back")
                case "Core": Text("Core")
                default:
                    Text("no selection")
                }
            }
        }.onAppear {
            workoutGen()
        }
    }
    
    func workoutGen() {
        workoutSelection = workouts.randomElement() ?? "workout selection"
    }
    
}