I'm creating a new iOS app using SwiftUI and need to display the contents of a text file in a Text view. I know how to load the contents of the file and store them in a string variable. My problem is finding the correct place to put that code so I can reference it when I create the Text view. Below is the code for the view that's hosting the Text view in question.
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"){})
}
}
I hope is helps. It used Bundle.main
to fetch file and ScrollView to display long text.
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")
}
}
}
I have made a better solution using the above answer from NikzJon. This retains simple text formatings such as bold titles in the license file.
import SwiftUI
class TextFileReaderModel: ObservableObject {
@Published public var data: LocalizedStringKey = ""
init(filename: String) { self.load(file: filename) }
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 = LocalizedStringKey(contents)
}
} catch let error as NSError {
print(error.localizedDescription)
}
} else {
print("File not found")
}
}
}
Usage:
struct IntellectualPropertyView: View {
@ObservedObject var model: TextFileReaderModel = TextFileReaderModel(filename: "licence")
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 20) {
Text(model.data).frame(maxWidth: .infinity)
}
.padding()
.navigationBarTitle("Legal Information")
}
}
}
finally create a Markdown version of your licence text file using a tool such as https://stackedit.io/app# . Then add it as a text file to your XCode project. It will retain formattings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With