当我尝试将 SwiftUI
NavigationSplitView
与 NSHostingController
一起使用时,导航侧边栏出现意外跳转。
当我按下窗口标题栏上的导航侧边栏按钮时,导航侧边栏按钮会跳转。
NSHostingController
来托管SwiftUI视图?感谢您的帮助,我已在下面附上相关的swift代码👇
ContentView.swift
struct ContentView: View {
@StateObject var navigation = NavigationChoice()
var body: some View {
NavigationSplitView {
List(selection: $navigation.selected) {
NavigationLink(value: "View 1") {
HStack(spacing: 12) {
Image(systemName: "house.fill")
.frame(width: 10)
Text(verbatim: "View 1")
}
}
NavigationLink(value: "View 2") {
HStack(spacing: 12) {
Image(systemName: "doc.badge.arrow.up.fill")
.frame(width: 10)
Text(verbatim: "View 2")
}
}
NavigationLink(value: "View 3") {
HStack(spacing: 12) {
Image(systemName: "gear.circle.fill")
.frame(width: 10)
Text(verbatim: "View 3")
}
}
Spacer()
}
} detail: {
if let selection = navigation.selected {
switch selection{
case "View 2":
View2()
default:
EmptyView()
}
}
}
.navigationTitle("My Navigation Title") //<---- this is my navigation title
.frame(width:1000, height: 600)
.fixedSize()
}
}
final class NavigationChoice: ObservableObject {
@Published var selected: String? = "View 2"
}
WindowController.swift
import Foundation
import SwiftUI
class WindowController {
private var window: NSWindow?
init() {
showWindow()
}
func showWindow() {
DispatchQueue.main.async {
self.window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 600, height: 600),
styleMask: [.titled, .closable, .resizable, .miniaturizable],
backing: .buffered,
defer: false
)
let myContentView = ContentView()
let hostingController = NSHostingController(rootView: myContentView)
guard let myWindow = self.window else { return }
myWindow.contentViewController = hostingController
myWindow.center()
myWindow.makeKeyAndOrderFront(nil)
myWindow.isReleasedWhenClosed = false
myWindow.display()
}
}
}
您可以将
.fullSizeContentView
添加到窗口的 styleMask
。
func showWindow() {
DispatchQueue.main.async {
self.window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 600, height: 600),
styleMask: [.titled, .closable, .resizable, .miniaturizable, .fullSizeContentView],
backing: .buffered,
defer: false
)
let myContentView = ContentView()
let hostingController = NSHostingController(rootView: myContentView)
guard let myWindow = self.window else { return }
myWindow.contentViewController = hostingController
myWindow.center()
myWindow.makeKeyAndOrderFront(nil)
myWindow.isReleasedWhenClosed = false
myWindow.display()
}
}