NSStatusBar
The NSStatusBar
class defines an object that manages a collection of NSStatusItem
objects displayed within the system-wide menu bar. A status item can be displayed with text or an icon, can provide a menu and a target-action message when clicked, or can be a fully customized view that you create.
NSMenu
An NSMenu object manages an application’s menus.
在平常打开MAC应用软件的时候,往往会在MAC上面的状态栏上出现对应图标,和Dock上出现打开的应用图标,这是如何设置的呢?
代码如下:
import Cocoa
class ViewController: NSViewController {
var status = NSStatusBar.system().statusItem(withLength: NSSquareStatusItemLength)
var customMenu = NSMenu()
override func viewDidLoad() {
super.viewDidLoad()
//设置点击状态图标时的响应事件
status.target = self
status.action = #selector(statusBarClicked(_:))
//设置状态图标
status.image = NSImage.init(named: "QQ")
//设置应用图标
NSApp.applicationIconImage = NSImage.init(named: "QQ1")
//NSMenu
customMenu.title = "Title"
customMenu.addItem(withTitle: "关于我们", action: #selector(clickMenuItem(_:)), keyEquivalent: "g")
customMenu.addItem(withTitle: "详细信息", action: #selector(clickMenuItem(_:)), keyEquivalent: "d")
customMenu.addItem(withTitle: "退出", action: #selector(NSApp.terminate(_:)), keyEquivalent: "q")
status.menu = customMenu
}
func statusBarClicked(_ sender:NSStatusItem){
print("statusBarClicked")
}
func clickMenuItem(_ sender:NSMenuItem){
print(sender.title)
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
效果图如下:
1.png 2.pngNSStatusBar中在没有添加自定义NSMenu情况下,可以添加点击事件,如果添加NSMenu,对应的点击事件无效
//设置点击状态图标时的响应事件
status.target = self
status.action = #selector(statusBarClicked(_:))
设置NSStatusItem的image属性,可以给item添加图片。如上图1。
NSMenu添加的NSMenuItem显示效果是第一张图的“关于我们”,“详细信息”和“退出”,每个NSMenuItem方法open func addItem(withTitle string: String, action selector: Selector?, keyEquivalent charCode: String) -> NSMenuItem
中对keyEquivalent设置,是点击键盘对应符号即可触发响应事件。
使用如下方法可以手动设置Dock图标,直接拖入图片到Assert里也可以设置Dock上的应用图标
//设置应用图标
NSApp.applicationIconImage = NSImage.init(named: "QQ1")
源码-->:github
网友评论