0

(Note there is a bit more than just setting the initial size) For example, if you just set the initial size, resize the view, close the document then reopen the size change will be lost) I spent too much time trying to make it work in MacOS 11.0 ( that's a requirement) The task is very basic Save the application position and size when closing it and restore when opening it again. Saving the actual data is pretty straightforward but setting the first view size appeared to be harder. Here is a mock up application, which always starts with the same size and position. How do I make it behave like a well designed application i.e. it should remember its size between closing and opening documents, and between application launches "

import SwiftUI


@main
struct MyApp: App {

    var body: some Scene {
        DocumentScene()
    }
}


struct DocumentScene: Scene {
    @State var t = "123"
    var body: some Scene {
        
        DocumentGroup(newDocument: V_WorkflowDocument()) {
            file in
            GeometryReader{
                geometry in
                TextEditor(text: $t)
                
            }
        }
    }
}
user2555515
  • 779
  • 6
  • 20
  • Does this answer your question? [SwiftUI window size for document based MacOs App](https://stackoverflow.com/questions/63153120/swiftui-window-size-for-document-based-macos-app) – marcprux Aug 09 '22 at 00:31
  • Maybe this will help. [How to access NSWindow from @main App using only SwiftUI?](https://stackoverflow.com/questions/63432700/how-to-access-nswindow-from-main-app-using-only-swiftui) – Chocoford Aug 09 '22 at 11:14

1 Answers1

0

My solution is to add WindowAccessor as background for my main window view. It's not perfect - the window jumps to its position, but it works...

class WindowObserver: NSObject {
    var observer: NSKeyValueObservation?
    init(window: NSWindow) {
        super.init()
        observer = window.observe(\.frame) { window, change in
            UserDefaults.standard.windowFrame = window.frame
        }
    }
    deinit {
        observer?.invalidate()
    }
}

struct WindowAccessor: NSViewRepresentable {

    @State var observer: WindowObserver?
    
    func makeNSView(context: Context) -> NSView {
        let view = NSView()
        DispatchQueue.main.async { [weak view] in
            guard let view, let window = view.window else { return }
            if let windowFrame = UserDefaults.standard.windowFrame {
                window.setFrame(windowFrame, display: true)
            }
            observer = WindowObserver(window: window)
        }
        return view
    }
    
    func updateNSView(_ nsView: NSView, context: Context) { }
    
}

The problem with this, is that it replaces SwiftUI delegate for the window... and the windows are not being managed correctly

Cherpak Evgeny
  • 2,659
  • 22
  • 29