我的应用程序具有AView-> BView-> CView-> DView的多层布局。
我改变
window.rootViewController
到BView以便“弹出” 2个顶视图,但是由于某些原因,当我回到BView时,无法单击NavigationLink。
有想法该怎么解决这个吗?好像BView不知道它变得可见。
AView.swift:
import SwiftUI
struct AView: View {
init() {
print("AView init")
}
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: BView()) {
Text("This is View A, now go to View B.")
}
}
}
}
}
struct BView: View {
init() {
print("BView init")
}
var body: some View {
NavigationLink(destination: CView()) {
Text("This is View B, now go to View C.")
}
}
}
struct CView: View {
init() {
print("CView init")
}
var body: some View {
NavigationLink(destination: DView()) {
Text("This is View C, now go to View D.")
}
}
}
struct DView: View {
init() {
print("DView init")
}
var body: some View {
Button(action: {
print("button pressed")
(UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.toBView()
},
label: {
Text("Back!")
})
}
}
SceneDelegate.swift:
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Create the SwiftUI view that provides the window contents.
let aView = AView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: aView)
self.window = window
window.makeKeyAndVisible()
}
}
func toBView() {
let bView = BView()
window?.rootViewController = UIHostingController(rootView: bView)
}
}
Asperi已经指出了问题..您正在将BView设置为根级别。实际上改变它,应该不是一个大问题。
但是回到您的问题,为什么NavigationLink
它将不再起作用。那是因为包含NavigationView
的ViewA不再位于RootLevel中。因此,仅在且仅当BView是根视图时,才需要提供一个新的NavigationView。
因此,在BView中添加一个参数isRootView
,当您从自己的窗口中调用该参数时,该参数只会设置为trueSceneDelegate
struct BView: View {
init(isRootView: Bool = false) {
print("BView init")
self.isRootView = isRootView
}
var isRootView : Bool = false
var body: some View {
if isRootView {
NavigationView {
NavigationLink(destination: CView()) {
Text("This is View B, now go to View C.")
}
}
}
else
{
NavigationLink(destination: CView()) {
Text("This is View B, now go to View C.")
}
}
}
}
这是来自SceneDelegate的呼叫
func toBView() {
let bView = BView(isRootView: true)
window?.rootViewController = UIHostingController(rootView: bView)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句