首页 > 解决方案 > 将标题设置为状态项可可的自定义视图

问题描述

我有自定义状态视图,我已将其设置为状态项视图属性。

- (id)initWithStatusItem:(NSStatusItem *)statusItem
{
    CGFloat itemWidth = [statusItem length];
    CGFloat itemHeight = [[NSStatusBar systemStatusBar] thickness];
    NSRect itemRect = NSMakeRect(0.0, 0.0, itemWidth, itemHeight);
    self = [super initWithFrame:itemRect];

    //isReachable = YES;
    if (self != nil) {
        _statusItem = statusItem;
        _statusItem.view = self;

        [self checkReachability];
    }
    return self;
}

- (void)drawRect:(NSRect)dirtyRect
{

    NSColor *tintColor = [NSColor blackColor];
    tintColor = (!_isReachable)?[NSColor grayColor]:(self.isHighlighted?[NSColor whiteColor]:([self isDarkStyle]?[NSColor whiteColor]:[NSColor blackColor]));

    self.image = [[NSImage imageNamed:@"icn_statusitem"] imageTintedWithColor:tintColor];

    [self.statusItem drawStatusBarBackgroundInRect:dirtyRect withHighlight:self.isHighlighted];

    NSImage *icon = self.image;
    NSSize iconSize = [icon size];
    NSRect bounds = self.bounds;
    CGFloat iconX = roundf((NSWidth(bounds) - iconSize.width) / 2);
    CGFloat iconY = roundf((NSHeight(bounds) - iconSize.height) / 2);
    NSPoint iconPoint = NSMakePoint(iconX, iconY);

    [icon drawAtPoint:iconPoint fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];

    //[self checkReachability];
}

我在这里初始化了状态栏,当它启动时会在状态项中显示图标。收到通知后,statusSpeedNotification我想将状态项图像更改为字符串。我试过这个它不工作

- (id)init
{
    self = [super init];
    if (self != nil)
    {
        // Install status item into the menu bar
        statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength];
        _statusItemView = [[StatusItemView alloc] initWithStatusItem:statusItem];
        _statusItemView.image = [NSImage imageNamed:@"icn_statusitem"];
        _statusItemView.alternateImage = [NSImage imageNamed:@"icn_statusitem"];
        _statusItemView.action = @selector(togglePanel:);
        [[NSNotificationCenter defaultCenter] addObserverForName:@"statusSpeedNotification" object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
            NSString *speed = note.userInfo[@"speed"];
            _statusItemView.image= nil;
            _statusItemView.alternateImage = nil;
              statusItem.button.title = speed;

        }];
    }
    return self;
}

任何建议都会更有帮助。

标签: objective-cmacosstatusbarnsstatusitem

解决方案


推荐阅读