【Mac】NSWindow 添加child window,如何居中

父窗口添加子窗口,常常会出现窗口不能居中显示,即使调用接口:

- (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接口是被自动调用的。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值