0

OK、これが私がやったことです:

  • を持っていますNSCollectionView
  • アイテムを「選択」し、アイテムが選択されたときにカスタム境界線を描画できるようにしたかった
  • サブクラス化NSCollectionViewItemしました (選択を可能にするため)
  • 境界線を描画するためにNSView、ビューをサブクラス化しましたNSCollectionViewItem

コード

ビューアイテム

@implementation MSLibraryCollectionViewItem

- (void)setSelected:(BOOL)flag
{
    [super setSelected:flag];
    [(MSLibraryCollectionViewView*)[self view] setSelected:flag];
    [(MSLibraryCollectionViewView*)[self view] setNeedsDisplay:YES];
}

カスタム ビュー

@implementation MSLibraryCollectionViewView

/***************************************
 Initialisation
 ***************************************/

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

    return self;
}

/***************************************
 Drawing
 ***************************************/

- (void)drawRect:(NSRect)rect
{
    if ([self selected]) {
        //[[NSColor redColor] setFill];
        //NSRectFill(rect);
        //[super drawRect:rect];

            NSColor* gS = [NSColor colorWithCalibratedRed:0.06 green:0.45 blue:0.86 alpha:1.0];
        NSColor* gE = [NSColor colorWithCalibratedRed:0.12 green:0.64 blue:0.94 alpha:1.0];
        NSGradient* g = [[NSGradient alloc] initWithStartingColor:gE endingColor:gS];
        NSColor *borderColor = [NSColor colorFromGradient:g];

        NSRect frameRect = [self bounds];

        if(rect.size.height < frameRect.size.height)
            return;
        NSRect newRect = NSMakeRect(rect.origin.x+5, rect.origin.y+5, rect.size.width-10, rect.size.height-10);

        NSBezierPath *textViewSurround = [NSBezierPath bezierPathWithRoundedRect:newRect xRadius:7 yRadius:7];
        [textViewSurround setLineWidth:2.0];
        [borderColor set];
        [textViewSurround stroke];
    }
}

ただし、描画に問題があるようです。例えば:

  • コレクション ビューのコンテナーのサイズを変更すると、外側のボックスに奇妙な線が表示される
  • コレクション ビューのアイテムが 100% 表示されていない場合 (下にスクロールされているなど)、選択枠はまったく表示されません (表示されている部分だけを描画することを期待しています)。

いくつかの例

NSCollectionView 選択アイテムの描画の問題

NSCollectionView の描画の問題

どうしたの?


PS私は Cocoa での描画やカスタム ビューの第一人者ではありません。そのため、アイデアやヘルプは大歓迎です。

4

1 に答える 1