【问题标题】:How to add if else statement to a button and .sheet?如何将 if else 语句添加到按钮和 .sheet?
【发布时间】:2021-07-17 05:33:26
【问题描述】:

我是 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 条件或开关盒,以便我可以根据出现和被点击的按钮呈现不同的视图。 所以对腿部、背部、核心等有不同的看法。

【问题讨论】:

标签: ios swift xcode swiftui


【解决方案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"
    }
    
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 2019-04-09
    • 1970-01-01
    • 2022-01-25
    • 2019-07-04
    • 1970-01-01
    相关资源
    最近更新 更多