首页 > 解决方案 > 如何在 SwiftUI Mac 应用程序的帮助菜单中显示用户指南?

问题描述

我编写了一个 SwiftUI 应用程序并将其发布在 Mac App Store 上。我还编写了详细的用户指南和各种技术指南,以帮助用户了解如何使用该应用程序并解释其显示。所有这些 .md 文件都包含在我的应用程序中。如何允许帮助菜单打开和显示这些文件?

标签: iosswiftmacosswiftui

解决方案


我不知道其他人是如何做到这一点的,但这是我会使用的方法:

import SwiftUI


@main
struct MacApp: App {
    @State var showHelp = false
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .sheet(isPresented: self.$showHelp) { HelpView() }
        }.commands {
            CommandGroup(replacing: .help) {
                Button(action: {showHelp = true}) {
                    Text("App Help")
                }
            }
        }
    }
}

对于 iOS:

@main
struct IOSApp: App {
    @State var showHelp = false

    var body: some Scene {
        WindowGroup {
            ContentView(showHelp: $showHelp)
                .sheet(isPresented: self.$showHelp) { HelpView() }
        }
    }
}

传递showHelp(或作为ObservableObject/EnvironmentObject),然后设置showHelp=true,例如单击按钮时Image(systemName: "info.circle")

struct HelpView: View {
    @Environment(\.dismiss) var dismiss
    
    @State var mdText = AttributedString()
    
    var body: some View {
        VStack (alignment: .leading, spacing: 20) {
            Button(action: {dismiss()}) {
                Text("Done").foregroundColor(.blue)
            }.padding(10)
            ScrollView {
                Text("Welcome to my app help")
                Text(mdText)
            }.frame(width: 333, height: 333)
        }
        .onAppear {
            // get your .md files contents
            do {
                mdText = try AttributedString(markdown: "***help file contents***")
            } catch {
                // error
            }
        }
    }
}

EDIT1:读取md您的应用程序中包含的文件。

    .onAppear {
        var str: String = ""
        if let mdFile = Bundle.main.path(forResource: "README", ofType: "md") {
            do {
                str = try String(contentsOfFile: mdFile)
                mdText = try AttributedString(markdown: str)
            } catch {
                // deal with error
            }
        }
    }

EDIT2: ios 应用程序的内容视图:

struct ContentView: View {
    @Binding var showHelp: Bool  // <--- here
    
    var body: some View {
        Button(action: {showHelp = true}) {
          VStack {
            Image(systemName: "info.circle").resizable().frame(width: 60, height: 60)
            Text("Info").font(.caption)
          }.foregroundColor(Color.blue)
        }
    }
}

推荐阅读