我有一个NSCollectionView
正在显示一些图像。我已经实现了一个NSCollectionViewDelegate
告诉它应该选择和/或突出显示哪些项目。我正在使用股票NSCollectionViewItem
来绘制图像及其名称。当用户选择一个项目时,我的代表会收到有关突出显示状态更改的消息:
- (void)collectionView:(NSCollectionView *)collectionView
didChangeItemsAtIndexPaths:(NSSet<NSIndexPath *> *)indexPaths
toHighlightState:(NSCollectionViewItemHighlightState)highlightState
{
[collectionView reloadItemsAtIndexPaths:indexPaths];
}
我为didSelect
/做了类似的事情didDeselect
:
- (void)collectionView:(NSCollectionView *)collectionView
didSelectItemsAtIndexPaths:(nonnull NSSet<NSIndexPath *> *)indexPaths
{
[collectionView reloadItemsAtIndexPaths:indexPaths];
}
在NSCollectionViewItem
sview
中,我执行以下操作:
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
NSColor* bgColor = [[self window] backgroundColor];
NSColor* highlightColor = [NSColor selectedControlColor];
NSRect frame = [self bounds];
NSCollectionViewItemHighlightState hlState = [collectionViewItem highlightState];
BOOL selected = [collectionViewItem isSelected];
if ((hlState == NSCollectionViewItemHighlightForSelection) || (selected))
{
[highlightColor setFill];
}
else
{
[bgColor setFill];
}
[NSBezierPath fillRect:frame];
}
我看到的问题是绘制突出显示或选择似乎是随机的。当它绘制选择时,它几乎总是在用户实际选择的项目上(尽管由于某种原因它经常忽略最后一个项目)。有时,它会选择用户没有点击或拖过的不同项目。但是,通常它只是不绘制。
我添加了打印以验证它是否正在调用-didChangeItemsAtIndexPaths:toHighlightState:
和-didSelectItemsAtIndexPaths:
. 我在这里做错了什么吗?
我在视图的-drawRect:
方法中添加了一些日志记录,即使我-reloadItemsAtIndexPaths:
在-didChange*
方法中调用,它似乎也没有在所有转换中被调用。为什么不?
我还注意到,委托-should/didDeselectItemsAtIndexPaths:
似乎从未被调用过,即使-should/didSelectItemsAtIndexPaths:
确实被调用过。这是为什么?