NSCollectionView visibleRect 属性

NSCollectionView visibleRect property

NSCollectionView 显示多个项目。我有一个类似网格的布局。

我需要确定当前可见的项目。

根据documentation有一个方法

- (NSArray<NSCollectionViewItem *> *)visibleItems;

带有描述

The items returned by this method represent the ones that are active and currently being managed by the collection view. This array may contain items that are outside of the collection view’s actual visible rectangle. For example, it may contain items that were recently visible but have since been scrolled out of view. To test whether an item is actually visible, check to see if its frame rectangle intersects the visibleRect of the collection view.

所以我需要根据它的 frame 坐标和 collectionView 的 visibleRect 手动计算哪些项目是可见的。当然可以。

然而,困扰我的是哪个坐标visibleRect returns。

通常它同意 documentation here 如果我说

NSImage *img = [[NSImage alloc] initWithContentsOfFile:...];

[imageView setFrame:NSMakeRect(0., -100., 300., 400.)];
[imageView setImage:img];
NSLog(..., [imageView visibleRect]);
NSLog(..., [imageView frame]);

那么可见的矩形就会像预期的那样

x=0
y=100
width = 300
height = 300

这与文档完全一致。

但是,在 NSCollectionView 的情况下,它的行为不同。 如果我创建了项目并且显示了第一个项目,那么 visibleRect 将显示

x = 0
y = 0

现在,如果我向下滚动一点,输出将是

x = 0
y = some number > 0

但是,我希望它应该 return 一个不同的 y 值。因为

A view's visible rectangle reflects the portion of the contents that are actually displayed, in terms of the view's bounds coordinate system

假设项目之间没有间距且项目相同

x = 0
y = (numItems - 1) * itemHeight

这种行为当然不是问题。我可以使用这些值来计算基于 returned 值的东西。我想知道原因。

我错过了什么?

P.S。本质上 NSCollectionView visibleRect 及其项目的 frame 的行为就好像坐标系的原点在左上角,y 向下增加并且 x增加权利。

NSCollectionView 使用翻转坐标系。 见 flipped property of NSView and Flipped Coordinate Systems.