一開始我要宣告:
@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:
當用戶 ID 為 0 時,我點擊影像進入 Login():
struct Login: View {
@AppStorage("userid") var userid: Int = 0
var body: some View{
Button(action: {
userid = 777
}) {
Text("login")
}
}
}
通過單擊登錄將 AppStorage 用戶 ID 更改為 777,然后 Login() 視圖關閉,這是我不想要的,主視圖中的條件正確更改為目標: Profile() 并顯示下載的影像。
問題2:
當我點擊影像轉到 Profile() 時:
struct Profile: View {
@AppStorage("userid") var userid: Int = 0
var body: some View{
Button(action: {
userid = 0
}) {
Text("profile: logout")
}
}
}
單擊注銷然后視圖不會關閉,但顯然 AppStorage 用戶 ID 不會更改為 0,因為主視圖仍然顯示下載的影像,并且目標仍然是 Profile()。
如何正確執行此操作?
uj5u.com熱心網友回復:
我認為您需要查看的是允許您以編程方式顯示視圖的isActive引數。NavigationLink這是檔案。
您可以做的是創建一個類似的屬性hasLoggedIn并將其傳遞給LoginView和。查看我剛剛撰寫的代碼片段,我想它可以滿足您的需求。NavigationLinkProfileView
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 模式,因為它可能不是將所有內容都放在視圖中的最佳解決方案
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/487353.html
