如何加载文本文件的内容并将其显示在 SwiftUI 文本视图中?

Dav*_*e F 2 ios swift swiftui

我正在使用 SwiftUI 创建一个新的 iOS 应用程序,并且需要在文本视图中显示文本文件的内容。我知道如何加载文件的内容并将它们存储在字符串变量中。我的问题是找到放置该代码的正确位置,以便在创建文本视图时可以引用它。下面是托管相关文本视图的视图的代码。

struct LicenseView: View {
    var body: some View {
        Text("") // How do I populate this with the contents of a text file?
            .navigationBarTitle("License")
            .navigationBarItems(trailing: Button("Check In"){})
    }
}
Run Code Online (Sandbox Code Playgroud)

Nik*_*Jon 5

我希望是有帮助的。它用于Bundle.main获取文件和 ScrollView 以显示长文本。

import SwiftUI

struct TestView: View {
    @ObservedObject var model = Model()
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: LicenseView(model: model)){ Text("License") }
            }.padding()
        }
    }
}

struct LicenseView: View{
    @ObservedObject var model: Model
    var body: some View{
        ScrollView {
            VStack {
                Text(model.data).frame(maxWidth: .infinity)
            }
        }.padding()
        .navigationBarTitle("License")
        .navigationBarItems(trailing: Button("Check In"){})
    }
}

class Model: ObservableObject {
    @Published var data: String = ""
    init() { self.load(file: "data") }
    func load(file: String) {
        if let filepath = Bundle.main.path(forResource: file, ofType: "txt") {
            do {
                let contents = try String(contentsOfFile: filepath)
                DispatchQueue.main.async {
                    self.data = contents
                }
            } catch let error as NSError {
                print(error.localizedDescription)
            }
        } else {
            print("File not found")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)