0

I am trying to implement a basic macOS application in SwiftUI (3.0), and having trouble implementing zoom. What I am trying to accomplish is:

  1. Window will have a minimum size, that won't allow resizing smaller than this point
  2. Window will have a zoom size, which will get the size of the Views, and return an optimal window size that only contains the bounds of these views
  3. Window will be free to resize to bigger dimensions, only to return to step two when zoom is triggered

Sample code is below:

@main
struct ZoomApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
                .frame(minWidth: 50,
                       maxWidth: .infinity,
                       minHeight: 50,
                       maxHeight: .infinity)
        }
    }
}

struct ContentView: View {
    var body: some View {
        Text("This is an experimental piece of text.")
            .padding(50)
            .border(Color.red, width: 5)
            .fixedSize()
    }
}

I have already experimented with GeometryReader to a various degree, but haven't been able to succeed. It looks like geometry.size.width and geometry.size.height did not take the size of Text into account. I've tried it both on the parent and child view.

Basically I am looking for something like below:

Window

I think there must be a really easy way to do it, since this looks like textbook zoom behaviour.

Addendum: I figured out how to switch between minimum and optimal sizes with windowWillUseStandardFrame(_:).

extension NSWindowController: NSWindowDelegate {
    public func windowWillUseStandardFrame(_ window: NSWindow, defaultFrame newFrame: NSRect) -> NSRect {
        return NSRect(origin: window.frame.origin, size: CGSize(width: 500, height: 500))
    }
}

Now I need find out how to pass SwiftUI view constraints to this function.

fankibiber
  • 729
  • 1
  • 6
  • 19

0 Answers0