带有渐变填充的NSView?

Mik*_*e T 6 cocoa

我正在尝试用渐变填充NSView。当窗口处于背景中时,渐变应具有较浅的颜色以匹配窗口的其余部分。下面的代码有很多工件:第一次绘制窗口时,它是用背景色绘制的。调整窗口大小时,将使用前景色。当窗口移到后面时,没有按预期使用背景色。我不应该为此任务使用isKeyWindow吗?

- (void)drawRect:(NSRect)dirtyRect {

    if ([[self window] isKeyWindow]) {

        NSColor *startingColor = [NSColor colorWithCalibratedWhite:0.8 alpha:1.0];
        NSColor *endingColor = [NSColor colorWithCalibratedWhite:0.6 alpha:1.0];
        NSGradient* aGradient = [[NSGradient alloc]
                             initWithStartingColor:startingColor
                             endingColor:endingColor];
        [aGradient drawInRect:[self bounds] angle:270];

    } else {
        NSColor *startingColor = [NSColor colorWithCalibratedWhite:0.9 alpha:1.0];
        NSColor *endingColor = [NSColor colorWithCalibratedWhite:0.8 alpha:1.0];
        NSGradient* aGradient = [[NSGradient alloc]
                             initWithStartingColor:startingColor
                             endingColor:endingColor];
        [aGradient drawInRect:[self bounds] angle:270];
    }
    [super drawRect:dirtyRect];
}
Run Code Online (Sandbox Code Playgroud)

zpa*_*ack 3

我认为您所看到的行为是因为窗口在获得或失去关键状态时不一定会重新绘制。当窗口成为或退出密钥时,我会尝试强制更新窗口。就像是:

- (void) viewDidMoveToWindow
{
    if( [self window] == nil ) {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    else {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(forceUpdate)
                                                     name:NSWindowDidResignKeyNotification
                                                   object:[self window]];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(forceUpdate)
                                                     name:NSWindowDidBecomeKeyNotification
                                                   object:[self window]];
    }
}

- (void) forceUpdate
{
    [self setNeedsDisplay:YES];
}
Run Code Online (Sandbox Code Playgroud)