![](/img/trans.png)
[英]SwiftUI: How to Navigate from one view to another by clicking on a button
[英]SwiftUI navigate to a new view by pressing Button
我正在嘗試導航到一個名為 HomePageView 的新 SwiftUI 文件(目前只包含一個紅色背景和一個顯示主頁的文本。)下面的代碼我試圖與我的 Button 集成,這是我初始時的 3 個按鈕之一視圖即 ContentView。 沒有錯誤,但是當我運行我的代碼時,我的登錄按鈕顯示“登錄已點擊!” 文本,但不會帶我到 HomePageView。 我是否錯誤地使用了 NavigationLink? 我知道我將遇到的下一個問題是一個頁面上的多個按鈕通向不同的目的地,有什么簡單的方法可以解決這個問題,我正在嘗試標記方法?
注意:一些視圖文本中還有其他代碼只是圖像和文本字段,以及另外兩個按鈕
@State private var current: Int? = nil
var body: some View {
NavigationLink(destination: HomePageView(), tag: 1, selection: self.$current) {
EmptyView()
}
Button(action: {
self.current = 1
print("Login tapped!")
}) {
Text("Login")
.fontWeight(.bold)
.foregroundColor(.orange)
.frame(width: deviceSize.size.width*(275/375), height: deviceSize.size.height*(45/812))
.cornerRadius(50)
.overlay(
Capsule(style: .continuous)
.stroke(Color.orange, style: StrokeStyle(lineWidth: 2)))
.frame(width: deviceSize.size.width, alignment: .center)
}.offset(y: deviceSize.size.height*(560/812))
}
如果我的想法如下代碼也與您的想法有關,請糾正我。
var body: some View {
NavigationView {
NavigationLink(destination: HomePageView(), tag: 1, selection: self.$current) {
Button(action: {
print("AAAA")
}) {
Text("Login")
.fontWeight(.bold)
.foregroundColor(.orange)
.frame(width: deviceSize.size.width*(275/375), height: deviceSize.size.height*(45/812))
.cornerRadius(50)
.overlay(
Capsule(style: .continuous)
.stroke(Color.orange, style: StrokeStyle(lineWidth: 2)))
.frame(width: deviceSize.size.width, alignment: .center)
}
}
}
}
如果像上面那樣,那更正發生在你身上的事情,因為它只是識別按鈕的動作。 解決這個只是刪除按鈕,只在 NavigationLink 中放置文本,如下所示:
var body: some View {
NavigationView {
NavigationLink(destination: HomePageView(), tag: 1, selection: self.$current) {
Text("Login")
.fontWeight(.bold)
.foregroundColor(.orange)
.frame(width: deviceSize.size.width*(275/375), height: deviceSize.size.height*(45/812))
.cornerRadius(50)
.overlay(
Capsule(style: .continuous)
.stroke(Color.orange, style: StrokeStyle(lineWidth: 2)))
.frame(width: deviceSize.size.width, alignment: .center)
}
}
}
在我的項目中,我使用了另一種解決方案。 我不知道這是否也適合你:
A 創建了一個母視圖
if current == 0 {
CurrentView()
} else {
HomePageView()
}
您還可以使用withAnimation()
設置動畫(請參閱https://developer.apple.com/documentation/swiftui/3279151-withanimation )
如果你想看看我的實現,你可以在這里看到它: https : //github.com/tristanratz/ChatApp/blob/master/ClientApp/MainView.swift
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.