问题描述
我正在使用SwiftUI
和新的App
生命周期来构建macOS应用。
我很想更改“关于窗口”(当您点击应用菜单中的“关于DemoApp”时显示)的内容,但是不知道如何:
如何用自定义视图替换“关于”视图?
解决方法
您需要将Credits.rtf文件添加到Bundle中。这将被自动检测并插入“关于”对话框中。
您可以找到更多here
,您可以这样做,但它确实需要创建一个 AppDelegate。您的 AppFile 应如下所示:
struct MyApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
MainView()
}
.commands {
CommandGroup(replacing: CommandGroupPlacement.appInfo) {
Button(action: {
appDelegate.showAboutPanel()
}) {
Text("About My App")
}
}
}
}
}
你的 AppDelegate 应该是这样的:
class AppDelegate: NSObject,NSApplicationDelegate {
private var aboutBoxWindowController: NSWindowController?
func showAboutPanel() {
if aboutBoxWindowController == nil {
let styleMask: NSWindow.StyleMask = [.closable,.miniaturizable,/* .resizable,*/ .titled]
let window = NSWindow()
window.styleMask = styleMask
window.title = "About My App"
window.contentView = NSHostingView(rootView: AboutView())
aboutBoxWindowController = NSWindowController(window: window)
}
aboutBoxWindowController?.showWindow(aboutBoxWindowController?.window)
}
}
然后,只需创建一个名为 AboutView 的 SwiftUI 视图,它就会在您的“关于”框中显示该视图。例如:
struct AboutView: View {
var body: some View {
VStack {
Spacer()
HStack {
Spacer()
Text("Hello,World!")
Spacer()
}
Spacer()
}
.frame(minWidth: 300,minHeight: 300)
}
}