弹出窗口在 iPad 应用程序中大量使用,我真的很喜欢它们。现在我考虑如何在 Mac 上的 AppKit 中实现这一点,因为我有一个它的用例。
我是否需要 NSWindow 子类来完成覆盖,或者我也可以使用普通 View 吗?
最佳答案
根据Apple's Developer Documentation ,您可以通过内置 NSPopover 类在 OS X 上使用内置弹出框:
Starting in OS X v10.7, AppKit provides support for popovers by way of the NSPopover class. A popover provides a means to display additional content related to existing content on the screen. The view containing the existing content—from which the popover arises—is referred to in this context as a positioning view. You use an anchor to express the relation between a popover and its positioning view.
这里是 NSPopover class 的链接。您还可以查看日历 (10.7+) 应用程序和 Safari 应用程序 (10.8+) 中使用的 NSPopovers 示例。下图描绘了日历应用程序(左)和 Safari(右)中的弹出窗口:
<小时/>
这是如何设置 NSPopover,它非常简单,并且主要可以在界面构建器中完成。
- 将 NSPopover 项添加到界面构建器中的 XIB 中。这将创建 NSPopover 及其 View Controller 。
- 接下来,通过界面生成器将自定义 NSView 拖到 XIB 中。这将是弹出 View Controller 的 View
- 使用弹出窗口中所需的任何控件自定义 NSView
在头文件 (.h) 中添加以下两行代码:
@property (assign) IBOutlet NSPopover *popover; - (IBAction)showPopover:(id)sender;
不要忘记将 socket 和操作连接到您的接口(interface)。
- 在您的实现中,合成弹出窗口并添加
showPopover
的方法 在
showPopover
方法中,添加以下行以显示弹出窗口:[[self popover] showRelativeToRect:[sender bounds] ofView:sender preferredEdge:NSMaxYEdge];
由您决定如何关闭弹出窗口;因为复制/粘贴有什么乐趣?您可以手动执行此操作(提示:尝试使用close
)或更改behavior
属性并让系统执行此操作(请参阅下面的编辑)。
祝你好运,希望这有帮助!
<小时/>编辑
正如 David in his comment 所指出的:
Another possibility for dismissing the popover is to set its behavior to Transient. This allows the user to click anywhere outside the popover to have it disappear
弹出窗口的行为属性设置它的显示和消失方式。共有三种行为:
NSPopoverBehaviorApplicationDefined
-(默认)您的应用必须自行关闭弹出窗口NSPopoverBehaviorTransient
- 当任何界面元素与弹出窗口外部交互时,弹出窗口将关闭NSPopoverBehaviorSemitransient
- 当弹出窗口呈现 View 中的任何界面元素与弹出窗口外部交互时,弹出窗口将关闭。
在 Apple's Documentation 中了解更多相关信息.
关于cocoa - 我们可以在 Mac Cocoa 应用程序中使用弹出窗口吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4609162/