父窗口添加子窗口,常常会出现窗口不能居中显示,即使调用接口:
- (void)center;
仍然会存在垂直不居中的问题,那应该如何处理呢?
从文档中看:
The window is placed exactly in the center horizontally and somewhat above center vertically. Such a placement carries a certain visual immediacy and importance. This method doesn’t put the window onscreen, however; use makeKeyAndOrderFront:
to do that.
You typically use this method to place a window—most likely an alert dialog—where the user can’t miss it. This method is invoked automatically when a panel is placed on the screen by the runModalForWindow:
method of the NSApplication
class.
这个接口,只能保证子窗口在水平上居中,而垂直是不能保证的;
那么,我们需要手工设置一下居中的属性:
CGFloat xPos = NSWidth([[window screen] frame])/2 - NSWidth([window frame])/2;
CGFloat yPos = NSHeight([[window screen] frame])/2 - NSHeight([window frame])/2;
[window setFrame:NSMakeRect(xPos, yPos, NSWidth([window frame]), NSHeight([window frame])) display:YES];
上述代码,是计算窗口居中的位置,通过setFrame来实现;
但是改区域不包含顶部的menu和底部的dock bar,如果要计算上这两个部分,那么需要把代码中的
[[window screen] frame]
替换成:
[[window screen] visibleFrame]
另外,如果是模特窗口,即通过runModalForWindow来启动窗口,则center接口是被自动调用的。