你如何将状态项的标题设为图像而不是文本?

Jos*_*hua 1 cocoa objective-c

我为我的应用程序创建了一个状态项(菜单栏项),但目前它的标题是文本,我如何让它显示图像?

这是设置标题的代码的一部分.我需要更改为该代码才能显示图像?

[item setTitle:@"MenuItem"];
Run Code Online (Sandbox Code Playgroud)

Ale*_*ski 8

您使用setImage:方法,为其提供NSImage要在菜单栏上显示的方法.

另请注意,您可以NSStatusItem显示图像文本,例如使用电池指示灯.

以下是将图像设置为名为的文件的小示例OtherImage.jpg:

NSImage *statusItemImage = [NSImage imageNamed:@"OtherImage"];
if( !statusItemImage ) {
  NSLog(@"ERROR: Could not load the image for 'OtherImage.png'");
} else {
  [item setImage:statusItemImage];
}
Run Code Online (Sandbox Code Playgroud)

确保文件OtherImage.png实际上已添加到Xcode项目中并复制到应用程序的Resources目录中.如果您的图像未加载,则表示该文件未正确命名,实际上不是图像,或实际上未在应用程序包中.

  • 首先加载图像.您可以使用类似NSImage*statImage = [NSImage imageNamed:@"MyStatusImage"]; 只需确保MyStatusImage.png或其他任何内容实际位于应用程序的资源文件夹中. (2认同)