我正在使用 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/