Custom NSMenu like view not displaying selectedMenuItemColor correctly

懵懂的女人 提交于 2019-12-05 02:05:16

问题


I wrote my own NSMenu like class to show dynamic search results below a NSSearchField in a borderless NSWindow. It's working well but doesn't draw the magic selectedMenuItemColor correctly if I add some padding to the top of the subview. I put a 5 pixel padding at the top of container view to mimic NSMenu and when I do it blue selected gradient looks off. A picture & code should make this clear:

Here is my drawRect code inside my item view (remember this is just a regular NSView):

-(void) drawRect:(NSRect)dirtyRect {
    CGRect b = self.bounds;
    if (selected) {

        [NSGraphicsContext saveGraphicsState];

        [[NSColor selectedMenuItemColor] set];
        NSRectFill( b );

        [NSGraphicsContext restoreGraphicsState];
        if (textField) {
            textField.textColor = [NSColor selectedMenuItemTextColor];
        }
    } else {
        [[NSColor clearColor] set];
       NSRectFillUsingOperation(b, NSCompositeSourceOver);
        if (textField) {
            textField.textColor = [NSColor blackColor];
        }
    }
}

回答1:


You have to get the pattern phase origin to match your view frame.

That is, selectedMenuItemColor is actually a pattern, not a color, and that pattern is designed to display "properly" in "standard menu item height" increments. Because you have added the padding, now it is not being drawn at the "standard" location.

Try this:

-(void) drawRect:(NSRect)dirtyRect {
    CGRect b = self.bounds;
    if (selected) {

       NSPoint origin = [self frame].origin;
       curContext = [NSGraphicsContext currentContext];
       [curContext saveGraphicsState];
       [curContext setPatternPhase: origin];

        [[NSColor selectedMenuItemColor] set];
        NSRectFill( b );

        [curContext restoreGraphicsState];
        if (textField) {
            textField.textColor = [NSColor selectedMenuItemTextColor];
        }
    } else {
        [[NSColor clearColor] set];
       NSRectFillUsingOperation(b, NSCompositeSourceOver);
        if (textField) {
            textField.textColor = [NSColor blackColor];
        }
    }
}


来源:https://stackoverflow.com/questions/9683192/custom-nsmenu-like-view-not-displaying-selectedmenuitemcolor-correctly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!