SwiftUI 通过按按钮导航到新视图



我正在尝试导航到一个名为HomePageView的新SwiftUI文件(目前仅由红色背景和显示主页的文本组成。下面的代码我试图与我的按钮集成,这是我初始视图上的 3 个按钮中的 1 个,即 ContentView。没有错误,但是当我运行我的代码时,我的登录按钮,它显示"登录点击!"文本,但不会将我带到主页视图。我是否错误地使用导航链接?我知道我将遇到的下一个问题是一页上有多个按钮通向不同的目的地,有什么简单的方法可以解决这个问题,我正在尝试标签方法?

注意:某些视图文本中还有其他代码,它们只是图像和文本字段,以及其他两个按钮

@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)
}

}
}
}

如果像上面一样,可以纠正发生在您身上的事情,因为它只是识别了按钮的操作。解决此只需删除按钮,仅将文本放入导航链接中,如下所示:

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

最新更新