Skip to content

Instantly share code, notes, and snippets.

@OskarGroth
Created November 20, 2020 12:56
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OskarGroth/3b729b251fce91f3386bd9ea76f7c8bd to your computer and use it in GitHub Desktop.
Save OskarGroth/3b729b251fce91f3386bd9ea76f7c8bd to your computer and use it in GitHub Desktop.
import Cocoa
import SwiftUI
public extension View {
func bindWindow(_ window: Binding<NSWindow?>) -> some View {
return background(WindowAccessor(window))
}
}
public struct WindowAccessor: NSViewRepresentable {
@Binding public var window: NSWindow?
public init(_ window: Binding<NSWindow?>) {
self._window = window
}
public func makeNSView(context: Context) -> NSView {
return WindowAccessorView(binding: $window)
}
public func updateNSView(_ nsView: NSView, context: Context) {}
}
class WindowAccessorView: NSView {
@Binding var windowBinding: NSWindow?
init(binding: Binding<NSWindow?>) {
self._windowBinding = binding
super.init(frame: .zero)
}
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
windowBinding = window
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment