簡體   English   中英

在 SwiftUI 中按下按鈕時更改視圖

[英]Change the view when a button is pressed in SwiftUI

當我按下 SwiftUI 中的按鈕時,我想更改視圖。

ZStack {
    Button(action: {
        Settings(logOutAfter24H: true, emailAddress: "example@example.com")
        print("Button pressed")
    }) {
        ZStack {
            RoundedRectangle(cornerRadius: 10)
                .frame(width: 125, height: 150).foregroundColor(Color.CGreen)
            HStack {
                Image(systemName: "gear")
                Text("Settings").foregroundColor(Color.black)
            }
        }
    }
}

我想切換到Settings視圖。

如果您只想將當前視圖替換為 SettingsView,您可以嘗試:

struct ContentView: View {
    @State var showSettingsView = false

    var body: some View {
        ZStack {
            if showSettingsView {
                Settings(...)
            } else {
                settingsButton
            }
        }
    }
    
    var settingsButton: some View {
        Button(action: {
            self.showSettingsView = true
            print("Button pressed")
        }) {
            ZStack {
                RoundedRectangle(cornerRadius: 10)
                    .frame(width: 125, height: 150).foregroundColor(.green)
                HStack {
                    Image(systemName: "gear")
                    Text("Settings").foregroundColor(Color.black)
                }
            }
        }
    }
}

通過設置showSettingsView的值,您可以決定是顯示還是隱藏 SettingsView。

或者,您可以使用NavigationLink在導航堆棧上推送新視圖或使用工作sheet以模態方式呈現視圖:

struct ContentView: View {
    @State var showSettingsView = false

    var body: some View {
        ZStack {
            settingsButton
        }
        .sheet(isPresented: $showSettingsView) {
            Settings(...)
        }
    }
    ...
}

為它制作一張工作表或導航鏈接。 對於工作表,創建一個名為 show = false 的 @State var。 然后在按鈕操作中說 self.show.toggle() ,然后在父視圖堆棧的右括號或按鈕的右括號中說.sheet並使用 $show 進行綁定,然后對內容進行綁定,只需說設置()。 如果您想創建導航鏈接,只需刪除按鈕並改為 NavigationLink(destination: Settings() { "configure button appearance here" }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM