为何NSView无法呈现指定尺寸?
解决NSView设置尺寸后窗口显示过小的问题
修正后的代码
class AppDelegate: NSObject, NSApplicationDelegate { private lazy var window: NSWindow = NSWindow() func applicationDidFinishLaunching(_ aNotification: Notification) { window.styleMask = [.titled, .fullSizeContentView] window.backingType = .buffered let blueView: NSView = NSView(frame: CGRect(origin: .zero, size: CGSize(width: 300, height: 300))) blueView.wantsLayer = true blueView.layer?.backgroundColor = NSColor.blue.cgColor window.contentView = blueView // 根据contentView的尺寸设置窗口frame window.setFrame(blueView.frame, display: true) window.setFrameAutosaveName("Main Window") window.makeKeyAndOrderFront(window) } }
问题原因与解释
- NSWindow实例默认不会自动适配contentView的尺寸,即便你给contentView设置了300x300的frame,窗口仍会使用系统默认的最小初始尺寸。
- 必须显式设置NSWindow的frame,直接基于contentView的尺寸来设置即可让窗口与自定义视图大小匹配。
进阶适配(可选)
如果需要窗口后续随contentView尺寸变化自动调整,可添加以下设置:
// 让contentView能随窗口调整大小 blueView.autoresizingMask = [.width, .height] // 允许窗口自动计算内容边框厚度 window.autorecalculatesContentBorderThickness = true
内容的提问来源于stack exchange,提问作者swiftPunk
相关产品推荐
相关产品推荐

