我们可以在Mac Cocoa应用中使用弹出窗口吗?

15

弹出框在iPad应用程序中被广泛使用,我非常喜欢它们。现在我在考虑如何在Mac上的AppKit中实现它,因为我有一个使用案例。

我需要一个NSWindow子类来完成覆盖吗?还是我也可以使用普通视图?

3个回答

22
根据苹果开发文档,您可以使用内置的NSPopover类在OS X上使用内置弹出窗口:
引用: 自OS X v10.7开始,AppKit通过NSPopover类提供对弹出窗口的支持。弹出窗口提供了一种显示与屏幕上现有内容相关的其他内容的方式。包含现有内容的视图 - 弹出窗口从中出现 - 在此上下文中称为定位视图。您使用锚点来表示弹出窗口与其定位视图之间的关系。
这里是NSPopover类的链接。您还可以看到在日历(10.7+)应用程序和Safari应用程序(10.8+)中使用NSPopovers的示例。下面的图片显示了日历应用程序(左侧)和Safari(右侧)中的弹出窗口:

Use of NSPopover in Mac OS X


以下是设置NSPopover的方法,非常简单,大部分可以在界面构建器中完成。

  1. Add an NSPopover Item to your XIB in interface builder. This will create the NSPopover and its view controller.
  2. Next, drag a custom NSView into your XIB through interface builder. This will be the view for the popover view controller
  3. Customize your NSView with any controls you need in your popover
  4. In your header file (.h) add the following two lines of code:

    @property (assign) IBOutlet NSPopover *popover;
    - (IBAction)showPopover:(id)sender;
    

    Don't forget to connect both the outlet and the action to your interface.

  5. In your implementation, synthesize the popover and add the method for showPopover
  6. In the showPopover method, add this line to show the popover:

    [[self popover] showRelativeToRect:[sender bounds] ofView:sender preferredEdge:NSMaxYEdge];
    

由于复制/粘贴并不好玩,你需要自己想办法关闭弹出框。你可以手动关闭(提示:尝试使用close),也可以更改behavior属性让系统来关闭(请参见下面的编辑)。

祝你好运,希望这有所帮助!


编辑

David在评论中所述

另一种关闭弹出窗口的方法是将其行为设置为短暂的。这允许用户单击弹出窗口外部的任何位置使其消失

弹出窗口的行为属性设置了它的出现和消失方式,有三种行为:

  • NSPopoverBehaviorApplicationDefined - (默认)您的应用程序必须自己关闭弹出窗口
  • NSPopoverBehaviorTransient - 当与弹出窗口外的任何界面元素进行交互时,弹出窗口将关闭
  • NSPopoverBehaviorSemitransient - 当与弹出窗口的呈现视图外的任何界面元素进行交互时,弹出窗口将关闭。

Apple的文档中了解更多信息。


2
+1 很棒的回答 - 编辑得很好。关闭弹出窗口的另一种可能是将其行为设置为瞬态。这允许用户单击弹出窗口外的任何位置使其消失。附言:记得进行2个连接(输出和操作)。 - David

12

如果我理解你的意思正确,你想要类似于MAAttachedWindow(由Matt Gemmell开发)的东西,它是开源的。

MAAttachedWindow


+1。这对我很有效,而且通过一些重命名也可以将其移植到iPhone上。 - sudo rm -rf

4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接