ios - 如何加载文本文件的内容并将其显示在 SwiftUI TextView 中?

标签 ios swift swiftui

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

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"){})
    }
}

最佳答案

希望对您有所帮助。它使用 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")
        }
    }
}

关于ios - 如何加载文本文件的内容并将其显示在 SwiftUI TextView 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61581482/

相关文章:

SwiftUI : I get lost when I try to pass EnvironmentObject to another View when using MVVM

ios - 如何在 SwiftUI 中增加 navigationBarItem 的可点击区域?

ios - iOS iPhone 8 的 Xcode 运行时错误 - [AXRuntimeCommon] AX 查找问题 - errorCode :1100 portName :'com.apple.iphone.axserver' PID:2751

ios - 使用 RSSParser 进行 Today 扩展小组件

ios - 为什么核心动画类型采用字符串键路径?

swift - 错误 : Core Data Code generation is not supported for Swift 2. 3

javascript - HTML5 地理定位精度 Android 与 iO 有很大不同

ios - SwiftUI SceneDelegate 问题

swift - 从 Alamofire v3 迁移到 v4 后如何取消所有请求?

swift - 如何使用 SwiftUI 将按钮固定在 View 底部?