NSCollection查看项目间隙指示器的高度错误



我正在为macOS实现一个应用程序,其中我使用NSCollectionView作为时间线。为此,我使用自定义子类NSCollectionViewFlowLayout出于以下原因:

  1. 我希望项目只能水平滚动而不换行到下一行
  2. 似乎只有NSCollectionViewFlowLayout能够告诉NSCollectionView不要垂直滚动(灵感来自这里(

然而,所有这些都很顺利:我现在正在尝试实现项目的拖放重新排序。这也有效,但我注意到项目间间隙指示器(蓝线(没有正确显示,即使我确实返回了正确的尺寸。我计算它们如下:

override func layoutAttributesForInterItemGap(before indexPath: IndexPath) -> NSCollectionViewLayoutAttributes?
{
var result: NSCollectionViewLayoutAttributes? = nil
// The itemLayoutAttributes dictionary is created in prepare() and contains
// the layout attributes for every item in the collection view
if indexPath.item < itemLayoutAttributes.count
{
if let itemLayout = itemLayoutAttributes[indexPath]
{
result = NSCollectionViewLayoutAttributes(forInterItemGapBefore: indexPath)
result?.frame = NSRect(x: itemLayout.frame.origin.x - 4, y: itemLayout.frame.origin.y, width: 3, height: itemLayout.size.height)
}
}
else
{
if let itemLayout = itemLayoutAttributes.reversed().first
{
result = NSCollectionViewLayoutAttributes(forInterItemGapBefore: indexPath)
result?.frame = NSRect(x: itemLayout.value.frame.origin.x + itemLayout.value.frame.size.width + 4, y: itemLayout.value.frame.origin.y, width: 3, height: itemLayout.value.size.height)
}
}
return result
}

根据文档,传递给方法的indexPath可以介于 0 和集合视图中的项数之间,包括我们是否尝试在最后一个项之后删除。如您所见,我为项目间间隙指示器返回一个矩形,该矩形应为 3 像素宽,高度与项目相同。

虽然指示器以正确的宽度显示在正确的 x 位置,但无论我通过什么高度,它都只有 2 个像素高。

我该如何解决这个问题?

注意:如果我临时更改布局以NSCollectionViewFlowLayout指示器会正确显示。

我正在覆盖NSCollectionViewFlowLayout中的以下方法/属性:

  • 准备((
  • 集合视图内容大小
  • layoutAttributesForElements(rect: NSRect( -> [NSCollectionViewLayoutAttributes]
  • layoutAttributesForItem(at indexPath: IndexPath( -> NSCollectionViewLayoutAttributes?
  • shouldInvalidateLayout(forBoundsChange newBounds: NSRect( -> Bool
  • layoutAttributesForInterItemGap(before indexPath: IndexPath( -> NSCollectionViewLayoutAttributes?

您可能还需要覆盖layoutAttributesForDropTarget(at pointInCollectionView: NSPoint) -> NSCollectionViewLayoutAttributes.

文档提到此方法返回的属性框架provides a bounding box for the gap, that will be used to position and size a drop target indicator(视图(。

您可以在绘制放置指示器后在拖放代码中设置断点(例如collectionView(:acceptDrop:indexPath:dropOperation:),然后在拖放会话期间命中断点时,运行 Xcode 视图调试器,在将放置指示器视图添加到集合视图后对其进行检查。这样,您可以确保视图层次结构正确,并且任何问题在视觉上都很明显。

最新更新