|
import SwiftUI |
|
|
|
struct BackButton: View { |
|
@State private var table: NSMapTable<NSString, NSWindow> = .strongToWeakObjects() |
|
|
|
var body: some View { |
|
Button("Back") { |
|
let visibleItems: [NSToolbarItem] = (table.object(forKey: "window")?.toolbar?.visibleItems)! |
|
let backItem = visibleItems.first(where: { $0.itemIdentifier.rawValue == "com.apple.SwiftUI.navigationStack.back" })! |
|
|
|
// SwiftUI.SwiftUISegmentedControl |
|
let control = backItem.view!.subviews.first!.subviews.first! as! NSSegmentedControl |
|
|
|
let target = control.target! |
|
let action = control.action! |
|
|
|
_ = target.perform(action, with: nil) |
|
} |
|
.onWindowChange { window in |
|
table.setObject(window, forKey: "window") |
|
} |
|
} |
|
} |
|
|
|
struct WindowReader: NSViewRepresentable { |
|
let windowHandler: @MainActor (NSWindow?) -> Void |
|
|
|
func makeNSView(context: Context) -> ContentView { |
|
ContentView(windowHandler: windowHandler) |
|
} |
|
|
|
func updateNSView(_ nsView: ContentView, context: Context) { |
|
nsView.windowHandler = windowHandler |
|
} |
|
|
|
final class ContentView: NSView { |
|
var windowHandler: @MainActor (NSWindow?) -> Void |
|
|
|
init(windowHandler: @escaping (NSWindow?) -> Void) { |
|
self.windowHandler = windowHandler |
|
super.init(frame: .zero) |
|
} |
|
|
|
required init?(coder: NSCoder) { |
|
fatalError("init(coder:) has not been implemented") |
|
} |
|
|
|
override func viewDidMoveToWindow() { |
|
super.viewDidMoveToWindow() |
|
windowHandler(window) |
|
} |
|
} |
|
} |
|
|
|
extension View { |
|
func onWindowChange(_ windowHandler: @escaping (NSWindow?) -> Void) -> some View { |
|
self |
|
.overlay { |
|
WindowReader(windowHandler: windowHandler) |
|
} |
|
} |
|
} |