【问题标题】:Display NSPopover in NSCollectionView?在 NSCollectionView 中显示 NSPopover?
【发布时间】:2026-01-17 10:40:01
【问题描述】:

(注意:问题has been asked before,一年多以前的结果还没有定论。希望我们现在了解更多并可以解决它?)

我试图在双击 NSCollectionItem 时在 NSPopover 上显示它。我的 NSCollectionView 设置正确并接收输入。

(如果我将代码复制粘贴到其他 NSView 子类,它工作得很好。NSCollectionView 有一些东西似乎把事情搞砸了。)

代码:

BIECollectionViewItem.h

#import <Cocoa/Cocoa.h>

@class BIEAppDelegate;

@interface BIECollectionViewItem : NSView {
    IBOutlet NSPopover *popover;
}

@end

BIECollectionViewItem.m

#import "BIECollectionViewItem.h"

@implementation BIECollectionViewItem

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
    }

    return self;
}

- (void)drawRect:(NSRect)dirtyRect
{
    // Drawing code here.
}

- (void)mouseDown:(NSEvent *)theEvent {
    [super mouseDown: theEvent];
    if([theEvent clickCount] == 2){
        [popover showRelativeToRect: [self bounds] ofView: self preferredEdge: NSMaxYEdge];
    }
}

@end

如果我在 mouseDown 事件中添加日志语句,我可以确认该事件正在被触发。但是,NSPopover 拒绝出现!

有谁知道如何让 NSPopover 出现在 NSCollectionView 上?

【问题讨论】:

  • 你在哪里allocinitNSPopover
  • 我不是; Interface Builder 正在为我处理这个问题。我刚刚从 IB 库中拖了一个NSPopover。然后它自动创建了一个NSPopover 对象、一个NSViewController(标记为“Popover View Controller”)和一个NSView,其中包含我希望出现在popover 中的界面项。我已经在主窗口中测试过了,一切正常,但是当我把它放到NSCollectionView 时,它就没有出现。

标签: objective-c nscollectionview nscollectionviewitem nspopover


【解决方案1】:

不确定你是否已经解决了这个问题,但我之前已经解决了这个问题。 我最近想在 NSCollectionViewItem 中显示相对于 NSTextField 的 NSPopOver。我没有遇到任何麻烦,除了有一次我得到了 relativeToRect: 参数错误,并且弹出窗口不会显示。在显示弹出窗口时,我总是使用相同的格式

NSView *someView; // defined elsewhere
[MyPopOver showRelativeToRect:[someView bounds] ofView:someView preferredEdge:NSMaxXEdge];

我只能建议确保你拥有正确的价值观,并且你没有在 IB 中犯过一些愚蠢的错误,比如忘记绑定或连接(我的失败中有 90%)。

希望这对您的问题有所帮助

【讨论】: