我是一名老 iOS 开发人员,现在我想做一个简单的 OS X 状态栏应用程序。我需要在 NSStatusItem 处添加一个标题,但它应该分两行,例如iStatPro网络功能。
我应该如何添加它?
我是一名老 iOS 开发人员,现在我想做一个简单的 OS X 状态栏应用程序。我需要在 NSStatusItem 处添加一个标题,但它应该分两行,例如iStatPro网络功能。
我应该如何添加它?
这是一个非常简单的例子。这个例子显示了两条带有两个简单闪烁灯的线。
它使用一个 NSView(自定义视图),其中包含两个 NSTextField 和两个 NSImageWell。
红光和绿光图像被添加到项目中并设置到 IB 中的图像井中。


.m
//
//  AppDelegate.m
//  Drawing Strings
//
//  Created by Mark Hunte on 07/10/2013.
//  Copyright (c) 2013 Mark Hunte. All rights reserved.
//
#import "AppDelegate.h"
@implementation AppDelegate
NSStatusItem *statusItem;
-(void)awakeFromNib{
    //-- SET UP ATTRIBUTED TEXT FOR THE LINES. WHICH GIVES US MORE CONTROL OVER THE TEXT IF WE WANT IT.
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    //--SET THE HEIGHT OF THE LINES
    paragraphStyle.maximumLineHeight = 12.f;
    //-- TEXT FOR NSTEXTFIELD 1
    NSAttributedString *attributedString = [[NSAttributedString alloc]
                                            initWithString:@"Line 1"attributes: [NSDictionary
                                                                                 dictionaryWithObjectsAndKeys: [NSColor blackColor], NSForegroundColorAttributeName,paragraphStyle,NSParagraphStyleAttributeName ,nil]];
     //-- TEXT FOR NSTEXTFIELD 2
    NSAttributedString *attributedString2 = [[NSAttributedString alloc]
                                             initWithString:@"Line 2"attributes: [NSDictionary
                                                                                  dictionaryWithObjectsAndKeys: [NSColor blackColor], NSForegroundColorAttributeName,paragraphStyle,NSParagraphStyleAttributeName ,nil]];
    //--- SET THE TEXT
    [_textField1  setAttributedStringValue:attributedString];
    [_textField2  setAttributedStringValue:attributedString2];
    //--- SET UP THE STATUS BAR
    NSStatusBar *bar = [NSStatusBar systemStatusBar];
    statusItem =  [bar statusItemWithLength: NSVariableStatusItemLength]  ;
    //-- CONSTRAIN THE CUSTOM VIEWS SIZE
    [_customView setFrameSize: NSMakeSize(50, 22)];
    //--- ADD THE VIEW TO THE STATUS BAR ITEM
    [statusItem setView:_customView];
    //-- MAKE SURE IT DISPLAYS
    [ _customView display];
    [_customView  setNeedsDisplay:TRUE];
    //-- HIDE ONE OF THE IMAGE VIEWS
    [_greenLight   setHidden:TRUE];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    //-- SET UP A TIME TO BLINK THE TWO IMAGE VIEW LIGHTS
NSTimer *    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(blinkLights) userInfo:nil repeats:YES];
    [timer fire];
}
-(void)blinkLights{
    //-- IF IMAGE VIEW IS HIDDEN UNHIDE IT, IF SHOWN HIDE IT.
    [_greenLight   setHidden:![_greenLight isHidden]];
    [_redLight   setHidden:![_redLight isHidden]];
}
@end
我使用两个文本字段,因为我认为这将在需要时提供更好的控制。但是您可以使用一个并换行文本。@"第 1 行\n第 2 行"
我还必须设置一个最大行高来帮助文本对齐,并且不得不摆弄 IB 中的约束。
但结果是两行灯闪烁:


子类化一个 NSView,您可以在其中手动绘制文本(搜索绘制 NSString),然后将视图添加到状态项。