MacOS-改变默认Window的尺寸

更改MacOS工程的窗口尺寸和位置.

applicationDidFinishLaunching 方法中,窗口还未激活,mainWindow 并没有值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
modifyWindowSize()
}

// modify the window default size
func modifyWindowSize() {

guard let screen = NSScreen.main else {
print("screen is unavailable")
return
}

/**
NSApplication.shared.mainWindow 只有在窗口被激活时才会返回正确的值。如果窗口还没有成为主窗口,mainWindow 的值将为 nil。
*/
// guard let mainWindow = NSApplication.shared.mainWindow else {
// print("mainWindow is unavailable")
// return
// }

guard let mainWindow = NSApp.windows.first else {
print("mainWindow is unavailable")
return
}

let screenFrame = screen.visibleFrame

let width = 800.0
let height = 600.0

let x = NSMidX(screenFrame) - width * 0.5
let y = NSMidY(screenFrame) - height * 0.5

// 创建窗口尺寸相对屏幕中心的位置

let frame = NSMakeRect(x, y, width, height)

mainWindow.setFrame(frame, display: true)

}

MacOS-改变默认Window的尺寸
https://jackiedai.github.io/2024/12/24/015MacOS/001_MacModifyWindowSize/
Author
lingXiao
Posted on
December 24, 2024
Licensed under