Mac Dev Part 1 - Menu Bar
2019-02-28 本文已影响0人
遇见Miu
时间总是挤出来的
从今天开始进行记录和学习Mac开发
1.展示名为statusItembutton的图片到Mac的状态栏上(应该是叫状态栏吧)
AppDelegate.swift
let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
func applicationDidFinishLaunching(_ aNotification: Notification) {
if let button = statusItem.button {
button.image = NSImage(named: "statusItembutton")
button.action = #selector(showDetail(sender:))
}
}
@objc func showDetail(sender: NSStatusBarButton) {
print("nice")
}
效果:
小电视机.jpg2.工程不希望window和底部应用图标出现
Main.storyboard
取消 Is Initial Controller
就不会出现window
Info.plist
加入 Application is agent (UIElement) --- YES
不会出现应用图标
3.添加MenuButton下拉项(先这么叫...)
AppDelegate.swift
let menu = NSMenu()
menu.addItem(NSMenuItem(title: "Show Detail", action: #selector(showDetail(sender:)), keyEquivalent: "G"))
// 加分割线
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Quit", action: Selector("terminate:"), keyEquivalent: "q"))
statusItem.menu = menu
其中keyEquivalent
这个参数是快捷键,但是你必须把MenuButton点开下拉项才能用快捷键(可能有解决方法,之后会研究)
效果:
下拉项.jpg
4.添加MenuButton下弹显示控制器(先这么叫...)
AppDelegate.swift
let popover = NSPopover()
func applicationDidFinishLaunching(_ aNotification: Notification) {
if let button = statusItem.button {
button.image = NSImage(named: "statusItembutton")
button.action = #selector(showDetail(sender:))
}
popover.contentViewController = DetailViewController.loadFromNib()
}
// 下弹控制器
@objc func showDetail(sender: NSStatusBarButton) {
if popover.isShown {
popover.performClose(sender)
} else {
if let button = statusItem.button {
popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minY)
}
}
}
添加弹出控制器,并在sb中拖入控制器设置对应class和sb ID(其实我发现xib应该更方便一点)
DetailViewController.swift
class DetailViewController: NSViewController {
class func loadFromNib() -> DetailViewController {
let sb = NSStoryboard(name: "Main", bundle: nil)
return sb.instantiateController(withIdentifier: "DetailViewController") as! DetailViewController
}
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
}
runAPP即可弹出,效果:
下拉视图.jpg