我正在使用 swiftUI 制作 macOS 应用程序。我想将窗口的最小大小设置为 800, 500。还有一个问题,如果我关闭窗口,然后重新打开,它会重新打开为上次关闭时的位置大小。我如何让它不记得上次关闭时的窗口位置和大小。我正在使用 Xcode 11.2.1 和 macOS Catalina,我正在为 macOS 而不是 iOS 开发一个应用程序。我该怎么做这两件事?
Asp*_*eri 13
如果您从基于 macOS SwiftUI 的模板创建项目,那么您需要做的所有更改都在 AppDelegate.swift 中。
窗口的大小是由内容定义的,因此您需要指定根内容视图框架,并且要禁止保存窗口位置需要 remove setFrameAutosaveName,因此您的 AppDelegate 应如下所示
@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)
}
...
Run Code Online (Sandbox Code Playgroud)
较新版本的 Xcode(和模板)现在使用SwiftUI App生命周期,而不是AppKit App Delegate。在这种情况下,您可以使用Layout.frame方法设置窗口大小(或任何 SwiftUI 视图的大小)来设置边界。就像使用任何修饰符一样:
VStack {
Text("You are Logged In")
Button(action: {
self.loggedIn = false
}, label: {
Text("Logout")
})
}
.frame(minWidth: 400, idealWidth: 600, minHeight: 450, idealHeight: 800)
Run Code Online (Sandbox Code Playgroud)
同样,它可以与任何 SwiftUI 视图一起使用,因此它是布局视图的便捷方法。
编辑:这个答案适用于所有平台,包括 macOS。
| 归档时间: |
|
| 查看次数: |
3176 次 |
| 最近记录: |