英文:
Why NSView is not be the given Size?
问题
以下是您提供的代码的翻译部分:
我正在创建一个 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
window.setFrameAutosaveName("Main Window")
window.makeKeyAndOrderFront(window)
}
}
如您所见,我已经为视图指定了所需的大小,但我无法设置窗口的大小,因为窗口是我的 NSView 的容器。只要为 NSView 指定所需的大小应该足够,但它不起作用!我也在使用一个主文件。
英文:
I am making a nsview and given the size but it does nothing and it is small, here the code:
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
window.setFrameAutosaveName("Main Window")
window.makeKeyAndOrderFront(window)
}
}
As you can see I gave the view the needed size but I cannot set the size for window, because window is container for my nsview, given needed size for nsview should be all it was needed but it does not work! I am using a main file as well.
答案1
得分: 0
你需要实际设置窗口的框架,例如:
window.setFrame(CGRect(origin: .zero, size: CGSize(width: 300, height: 300)), display: false)
仅在创建时为内容视图指定大小是不够的,因为一旦将其设置为内容视图,它将被调整大小以适应窗口。这在[这里][1]有记录。
> 窗口保留新的内容视图并在此后拥有它。视图对象被调整大小以精确适应窗口的内容区域。您可以通过其边界矩形修改内容视图的坐标系统,但不能直接更改其框架矩形(大小或位置)。
[1]: https://developer.apple.com/documentation/appkit/nswindow/1419160-contentview
英文:
You need to actually set the frame of the window, e.g.
window.setFrame(CGRect(origin: .zero, size: CGSize(width: 300, height: 300)), display: false)
Just giving the content view a size when you create it isn't enough because as soon as you set it as the content view, it is resized to fit the window instead. This is documented here.
> The window retains the new content view and owns it thereafter. The view object is resized to fit precisely within the content area of the window. You can modify the content view’s coordinate system through its bounds rectangle, but you can’t alter its frame rectangle (its size or location) directly.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论