如何使用 swiftUI 设置最小窗口大小,以及如何使窗口在启动时使用指定的大小和位置? [英] How do I set the minimum window size with swiftUI, and how do I make the window use the specified size and position when launching?

查看:84
本文介绍了如何使用 swiftUI 设置最小窗口大小,以及如何使窗口在启动时使用指定的大小和位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 swiftUI 制作 macOS 应用程序.我想将窗口的最小大小设置为 800, 500.还有一个问题,如果我关闭窗口,然后重新打开,它会重新打开为上次关闭时的位置大小.我如何让它不记得上次关闭时的窗口位置和大小.我正在使用 Xcode 11.2.1 和 macOS Catalina,我正在为 macOS 而不是 iOS 开发一个应用程序.我该怎么做这两件事?

I am making a macOS app with swiftUI. I want to set the minimum size of the window to 800, 500. Also there is this thing that if I close the window, and reopen, it reopens as the size an position from when it last closed. How do I make it not remember the window position and size from when it last closed. I am using Xcode 11.2.1 and macOS Catalina, and I am making an app for macOS, not iOS. How can I do these two things?

推荐答案

如果您从基于 macOS SwiftUI 的模板创建项目,那么您需要做的所有更改都在 AppDelegate.swift 中.

If you created project from template for macOS SwiftUI based, then all changes you need to do is in AppDelegate.swift.

窗口的大小是由内容定义的,因此您需要指定根内容视图框架,并且要禁止保存窗口位置,您需要删除setFrameAutosaveName,因此您的 AppDelegate 应该看起来像关注

The size of window is content-defined, so you need to specify root content view frame, and to disallow window position saving you need to remove setFrameAutosaveName, as a result your AppDelegate should look like the following

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    var window: NSWindow!

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Create the SwiftUI view that provides the window contents.
        let contentView = ContentView()
            .frame(minWidth: 800, maxWidth: .infinity, minHeight: 500, maxHeight: .infinity)

        // Create the window and set the content view. 
        window = NSWindow(
            contentRect: NSRect(x: 0, y: 0, width: 800, height: 500),
            styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
            backing: .buffered, defer: false)
        window.center()
        window.contentView = NSHostingView(rootView: contentView)
        window.makeKeyAndOrderFront(nil)
    }
    ...

这篇关于如何使用 swiftUI 设置最小窗口大小,以及如何使窗口在启动时使用指定的大小和位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆