如何修改Swift脚本运行时的菜单栏标题、Dock显示标题与图标
解决方法
要修改运行脚本时菜单栏、Dock栏的显示文本和图标,可以按如下步骤修改代码:
1. 修改Dock与菜单栏显示名称
导入CoreFoundation框架,调用CFBundleSetValue修改主Bundle的名称配置,即可替换默认的swift-frontend字样:
import CoreFoundation // 放在app初始化之后即可 CFBundleSetValue(CFBundleGetMainBundle(), kCFBundleNameKey, "自定义应用名称" as CFString)
2. 修改Dock栏图标
直接给NSApplication的applicationIconImage属性赋值自定义图片即可:
// 可以使用系统内置图标,也可以传入本地icns/png文件路径加载自定义图标 app.applicationIconImage = NSImage(contentsOfFile: "/path/to/your/custom/icon.icns") // 系统图标示例:NSImage(named: NSImage.folderName)
修改后的完整代码
import AppKit import Foundation import CoreFoundation let app = NSApplication.shared // 修改显示名称 CFBundleSetValue(CFBundleGetMainBundle(), kCFBundleNameKey, "我的自定义弹窗" as CFString) // 修改Dock图标,这里用系统的用户图标示例,可替换为自己的图标路径 app.applicationIconImage = NSImage(named: NSImage.userName) app.setActivationPolicy(.regular) // 该配置支持接收键盘输入且在Dock栏显示应用 let icon = NSImage(named: NSImage.cautionName) let a = NSAlert() a.messageText = "Delete the document?" a.icon = icon a.alertStyle = NSAlert.Style.informational a.informativeText = "Are you sure you would like to delete the document?" a.addButton(withTitle: "Ok") a.addButton(withTitle: "Cancel") app.activate(ignoringOtherApps: true) a.runModal()
可选优化:编译为独立可执行文件
如果直接运行脚本仍有残留标识,可以编译为独立可执行文件完全消除swift-frontend关联:
- 执行编译命令:
swiftc -o CustomAlert script.swift - 运行生成的可执行文件:
./CustomAlert
运行效果和直接跑脚本一致,不会再关联swift-frontend进程标识。
内容的提问来源于stack exchange,提问作者Gabriel
相关产品推荐
相关产品推荐

