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

标签 cocoa

弹出窗口在 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(右)中的弹出窗口:

Use of NSPopover in Mac OS X

<小时/>

这是如何设置 NSPopover,它非常简单,并且主要可以在界面构建器中完成。

  1. 将 NSPopover 项添加到界面构建器中的 XIB 中。这将创建 NSPopover 及其 View Controller 。
  2. 接下来,通过界面生成器将自定义 NSView 拖到 XIB 中。这将是弹出 View Controller 的 View
  3. 使用弹出窗口中所需的任何控件自定义 NSView
  4. 在头文件 (.h) 中添加以下两行代码:

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

    不要忘记将 socket 和操作连接到您的接口(interface)。

  5. 在您的实现中,合成弹出窗口并添加 showPopover 的方法
  6. 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/

相关文章:

objective-c - 从 tableView 返回什么 :objectValueForTableColumn:row:?

objective-c - 连接两个由 CRLF 分隔的 NSString

objective-c - 你如何比较 Swift 中的 NSFontSymbolicTraits 和 NSFontBoldTrait?

macos - 捆绑到 Cocoa 应用程序中的 Git 无法在 bundle 中找到帮助程序

macos - 以编程方式加载主界面?

objective-c - 从进程 ID 获取 CPU 信息

objective-c - 如何在 CAShapeLayer 上添加外发光

objective-c - stringWithContentsOfFile :encoding:error: error 260

iphone - 我真的需要在核心数据中始终存在双向关系吗?

objective-c - objc/cocoa 的类变量范围问题?