title: How to properly show the current selection in an NSCollectionView?
body: <p>I have an <code>NSCollectionView</code> that is showing some images. I have implemented an <code>NSCollectionViewDelegate</code> to tell it which items should be selected and/or highlighted. I'm using a stock <code>NSCollectionViewItem</code> to draw the images and their names. When the user selects an item, my delegate gets the messages about highlight state changes:</p>
  
  <pre><code>- (void)collectionView:(NSCollectionView *)collectionView
  didChangeItemsAtIndexPaths:(NSSet&lt;NSIndexPath *&gt; *)indexPaths
        toHighlightState:(NSCollectionViewItemHighlightState)highlightState
  {
      [collectionView reloadItemsAtIndexPaths:indexPaths];
  }
  </code></pre>
  
  <p>I do a similar thing for <code>didSelect</code>/<code>didDeselect</code>:</p>
  
  <pre><code>- (void)collectionView:(NSCollectionView *)collectionView
  didSelectItemsAtIndexPaths:(nonnull NSSet&lt;NSIndexPath *&gt; *)indexPaths
  {
      [collectionView reloadItemsAtIndexPaths:indexPaths];
  }
  </code></pre>
  
  <p>In the <code>NSCollectionViewItem</code>s <code>view</code>, I do the following:</p>
  
  <pre><code>- (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];
  }
  </code></pre>
  
  <p>The problem I'm seeing is that drawing the highlight or selection appears to be random. When it does draw the selection, it's almost always on the items the user has actually selected (though it often leaves off the last item for some reason). Occasionally, it will select a different item the user did not click on or drag over. Often, though, it just doesn't draw. </p>
  
  <p>I've added printing to verify that it is calling <code>-didChangeItemsAtIndexPaths:toHighlightState:</code> and <code>-didSelectItemsAtIndexPaths:</code>. Is there anything I'm doing wrong here? </p>
  
  <p>I've added some logging to the view's <code>-drawRect:</code> method, and it doesn't appear to be getting called on all transitions, even though I'm calling <code>-reloadItemsAtIndexPaths:</code> in the <code>-didChange*</code> methods. Why not? </p>
  
  <p>I've also noticed that the delegate's <code>-should/didDeselectItemsAtIndexPaths:</code> does not seem to get called ever, even though the <code>-should/didSelectItemsAtIndexPaths:</code> does get called. Why is that?</p>