Passing SwiftUI View size to AppKit?

Viewed 57

I'm using NSTabViewController to switch between SwiftUI Views, then resize my window frame size according to current View's size.

The question is, how can I pass the View's size to an AppKit Controller efficiently?

My code:

// My observable class

class SizeObservable: ObservableObject {
    static let shared = SizeObservable()
    
    @Published var firstSize: NSSize?
}
// My first test View

struct FirstView: View {
    @ObservedObject private var contentSize: SizeObservable = SizeObservable.shared
    
    var body: some View {
        VStack {
            Text("First")
        }
        .frame(width: 400, height: 280)
        .background(GeometryReader { geo in
            Rectangle()
                .fill(Color.clear)
                .onAppear(perform: {
                    contentSize.firstSize = geo.size
                })
        })
    }
}
// In my window controller

func testSize() {
    var firstSize: NSSize!

    SizeObservable.shared.$firstSize.sink { size in
        print(size)  // Breakpoint here
        firstSize = size
    }
    .store(in: &subscribers)

    print(firstSize)  // Breakpoint here
}

And I got below outputs:

nil
nil
Optional((400.0, 280.0))

Corresponding to breakpoints order: size(nil) -> firstSize(nil) -> size(Optional((400.0, 280.0)))

This means that I assigned nil to firstSize the first time I got size, just before size becomes Optional((400.0, 280.0)).

 

So how can I determine whether size is safe to use?

Or how can I pass my View's size to AppKit?

Any ideas? :)


0 Answers
Related