SwiftUI iOS -使用NavigationLink与条件和AppStorage时的错误 &g



开头我声明:

@AppStorage("userid") var userid: Int = 0

然后是下面的几行代码:

if(userid == 0){
NavigationLink(destination: Login(), label: {
Image(systemName: "person.circle.fill")
.resizable()
.aspectRatio(contentMode: .fit).frame(width: 32)
.foregroundColor(Color(UIColor(named: "IconColor")!))
})
}else{

NavigationLink(destination: Profile(), label: {
AsyncImage(url: URL(string: "https://cdn.icon-icons.com/icons2/2108/PNG/512/stackoverflow_icon_130823.png")) { phase in
switch phase {
case .empty:
Image(systemName: "person.circle.fill")
.resizable()
.aspectRatio(contentMode: .fit).frame(width: 32)
.foregroundColor(Color(UIColor(named: "IconColor")!))
case .success(let image):
image.resizable()
.aspectRatio(contentMode: .fit)
.frame(maxWidth: 32)
case .failure:
Image(systemName: "person.circle.fill")
.resizable()
.aspectRatio(contentMode: .fit).frame(width: 32)
.foregroundColor(Color(UIColor(named: "IconColor")!))
@unknown default:
Image(systemName: "person.circle.fill")
.resizable()
.aspectRatio(contentMode: .fit).frame(width: 32)
.foregroundColor(Color(UIColor(named: "IconColor")!))
}
}
})
}

问题1:

当userid为0时,点击图像进入Login():

struct Login: View {
@AppStorage("userid") var userid: Int = 0
var body: some View{

Button(action: {
userid = 777
}) {
Text("login")
}
}
}

通过点击login将AppStorage用户id更改为777,然后login()视图关闭,这是我不想要的,主视图中的条件正确更改为destination: Profile()并显示下载的图像。

问题2:

当我点击图片进入Profile():

struct Profile: View {
@AppStorage("userid") var userid: Int = 0
var body: some View{

Button(action: {
userid = 0
}) {
Text("profile: logout")
}
}
}

点击注销,那么视图不会关闭,但显然AppStorage userid不会更改为0,因为主视图仍然显示下载的图像,目标仍然是Profile()。

如何正确地做到这一点?

我认为您需要查看的是NavigationLinkisActive参数,它允许您以编程方式显示视图。

您可以做的是创建一个属性,如hasLoggedIn,并将其传递给LoginViewProfileViewNavigationLink。看看我刚刚写的代码片段,我猜它能满足你的要求。

struct MainView: View {
@AppStorage("userid") var userId: Int = 0
@State var hasLoggedIn = false
var body: some View {
NavigationView {
List {
if (userId == 0) {
NavigationLink {
LoginView(hasLoggedIn: $hasLoggedIn)
} label: {
Text("Login")
}
} else {
NavigationLink(isActive: $hasLoggedIn) {
ProfileView()
} label: {
Text("Profile")
}
}
}
}
}
}
struct LoginView: View {
@AppStorage("userid") var userId: Int = 0
@Binding var hasLoggedIn: Bool
var body: some View {
Button {
userId = 777
hasLoggedIn = true
} label: {
Text("Login")
}
}
}
struct ProfileView: View {
@AppStorage("userid") var userId: Int = 0
var body: some View {
Button {
userId = 0
} label: {
Text("Profile")
}
}
}
关于问题2,我没有面对它。你说的一切都很好,也许我误解你了。

哦,一定要看看MVVM模式,因为它可能不是把所有东西都放在视图中的最佳解决方案