在 macOS 开发中,如果你发现通过编程方式设置 NSWindow
的大小无效,可能是由于以下几个原因:
NSWindow
是 macOS 应用程序中的一个核心组件,代表了一个窗口。设置窗口大小通常涉及到调整窗口的 frame
属性。
NSWindow.StyleMask.resizable
,则窗口应该是可以调整大小的。NSWindow.StyleMask.resizable
,则窗口应该是可以调整大小的。以下是一个完整的示例,展示了如何在 macOS 应用程序中设置窗口大小:
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
var window: NSWindow!
func applicationDidFinishLaunching(_ aNotification: Notification) {
let initialWidth: CGFloat = 800
let initialHeight: CGFloat = 600
let styleMask: NSWindow.StyleMask = [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView]
window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: initialWidth, height: initialHeight),
styleMask: styleMask,
backing: .buffered,
defer: false)
// 设置窗口内容视图
let contentView = window.contentView!
contentView.wantsLayer = true
contentView.layer?.backgroundColor = NSColor.white.cgColor
// 尝试设置新的窗口大小
let newWidth: CGFloat = 1024
let newHeight: CGFloat = 768
window.orderOut(nil) // 隐藏窗口
window.setFrameSize(NSMakeSize(newWidth, newHeight)) // 设置新的窗口大小
window.makeKeyAndOrderFront(nil) // 重新显示窗口
}
}
通过上述方法,你应该能够解决通过编程方式设置 NSWindow
大小无效的问题。如果问题仍然存在,建议检查是否有其他代码或系统设置影响了窗口的行为。
领取专属 10元无门槛券
手把手带您无忧上云