我正在嘗試集成NavigationStack到我的應用程式中,SwiftUI我有四個視圖CealUIApp、OnBoardingView和。我想從用戶按下按鈕時導航到用戶按下按鈕時導航到UserTypeViewRegisterViewOnBoardingViewUserTypeViewOnBoardingViewUserTypeViewRegisterViewUserTypeView
下面是我的 CealUIApp 代碼
@main
struct CealUIApp: App {
@State private var path = [String]()
var body: some Scene {
WindowGroup {
NavigationStack(path: $path){
OnBoardingView(path: $path)
}
}
}
}
在OnBoardingView
Button {
path.append("UserTypeView")
} label: {
Text("Hello")
}.navigationDestination(for: String.self) { string in
UserTypeView(path: $path)
}
在UserTypeView
Button {
path.append("RegisterView")
} label: {
Text("Hello")
}.navigationDestination(for: String.self) { string in
RegisterView()
}
當按下按鈕時,UserTypeView我一直在導航到UserTypeView而不是在日志中RegisterView使用 msg說XcodeOnly root-level navigation destinations are effective for a navigation stack with a homogeneous path.
uj5u.com熱心網友回復:
您可以Only root-level navigation destinations are effective for a navigation stack with a homogeneous path通過將路徑型別更改為NavigationPath.
@State private var path: NavigationPath = .init()
但是隨后您會收到一條訊息/錯誤,我認為該訊息/錯誤可以更好地解釋該問題A navigationDestination for “Swift.String” was declared earlier on the stack. Only the destination declared closest to the root view of the stack will be used.
Apple 已決定掃描所有可用視圖的效率非常低,因此他們將navigationDestination優先使用 will。
試想一下,如果您OnBoardingView也可以選擇"RegisterView"
.navigationDestination(for: String.self) { string in
switch string{
case "UserTypeView":
UserTypeView(path: $path)
case "RegisterView":
Text("fakie register view")
default:
Text("No view has been set for \(string)")
}
}
SwiftUI 如何選擇合適的?
那么如何“修復”呢?你可以試試這個替代方案。
import SwiftUI
@available(iOS 16.0, *)
struct CealUIApp: View {
@State private var path: NavigationPath = .init()
var body: some View {
NavigationStack(path: $path){
OnBoardingView(path: $path)
.navigationDestination(for: ViewOptions.self) { option in
option.view($path)
}
}
}
//Create an `enum` so you can define your options
enum ViewOptions{
case userTypeView
case register
//Assign each case with a `View`
@ViewBuilder func view(_ path: Binding<NavigationPath>) -> some View{
switch self{
case .userTypeView:
UserTypeView(path: path)
case .register:
RegisterView()
}
}
}
}
@available(iOS 16.0, *)
struct OnBoardingView: View {
@Binding var path: NavigationPath
var body: some View {
Button {
//Append to the path the enum value
path.append(CealUIApp.ViewOptions.userTypeView)
} label: {
Text("Hello")
}
}
}
@available(iOS 16.0, *)
struct UserTypeView: View {
@Binding var path: NavigationPath
var body: some View {
Button {
//Append to the path the enum value
path.append(CealUIApp.ViewOptions.register)
} label: {
Text("Hello")
}
}
}
@available(iOS 16.0, *)
struct RegisterView: View {
var body: some View {
Text("Register")
}
}
@available(iOS 16.0, *)
struct CealUIApp_Previews: PreviewProvider {
static var previews: some View {
CealUIApp()
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/530625.html
標籤:IOS迅速迅捷
