cocoa - NSSegmentedCell 子类绘图

标签 cocoa subclass nssegmentedcontrol

我创建了 NSSegmentedCell 的子类并实现了drawWithFrame,如下所示:

#import "CustomSegmentedCell.h"

@implementation CustomSegmentedCell

- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView {

    int i=0, count=[self segmentCount];
    NSRect segmentFrame=cellFrame;

    for(i=0; i<count; i++) {
        segmentFrame.size.width=[self widthForSegment:i];
        [NSGraphicsContext saveGraphicsState];
        // Make sure that segment drawing is not allowed to spill out into other segments
        NSBezierPath* clipPath = [NSBezierPath bezierPathWithRect: segmentFrame];
        [clipPath addClip];
        [self drawSegment:i inFrame:segmentFrame withView:controlView];
        [NSGraphicsContext restoreGraphicsState];
        segmentFrame.origin.x+=segmentFrame.size.width;
    }

    _lastDrawRect=cellFrame;

}

@end

问题是分段在第一次启动应用程序时没有绘制,只有当我用鼠标单击分段控件应该绘制的空白区域时,它才可见。请告诉我,我在这里缺少什么。

谢谢

最佳答案

子类化并实现drawSegment:inFrame:withView:

- (void)drawSegment:(NSInteger)segment inFrame:(NSRect)frame withView:(NSView *)controlView
{
    NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:frame xRadius:8 yRadius:8];
    [path setClip];
    [path setLineWidth:2.5];
    [[NSColor grayColor] setStroke];
    NSColor* bgColr;
    if (segment%2) {
        bgColr = [NSColor blackColor];
    }
    else {
        bgColr = [NSColor redColor];
    }

    [bgColr setFill];
    [NSBezierPath fillRect:frame];  

}

关于cocoa - NSSegmentedCell 子类绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12000720/

相关文章:

cocoa - 如何自定义 NSSegmentedControl 字体和背景颜色

objective-c - 尝试在 OS X 中卸载卷时解释返回值(反对者)

cocoa - 检测/检查 NSView (NSResponder) 中的字符序列

objective-c - 创建目录AtPath : doesn't work

python - 如果父类(super class)自定义了深拷贝,如何定义子类的深拷贝

wpf - 让数据绑定(bind) WPF Listbox 生成子类 ListboxItems

cocoa - 获取WebView的总滚动大小(HTML内容的大小)

java - 为什么我不能更改子类值

xcode - 如何设置 NSSegmentedControl 的外观以匹配 Xcode 的外观?

macos - 在NSToolbar中实现NSSegmentedControl来控制NSTabViewController