First time using swift and this is what I've gathered so far. I'm not sure why the HomeContentView isn't displaying the content dynamically based on filemanager.directoryFiles
. Is there a simple way to display the content of an Outer view dynamically based on a state present within an Inner view?
import SwiftUI
struct FileManagerView: View {
@State private var directoryFiles: String
fileprivate init(directoryFiles: String) {
self.directoryFiles = directoryFiles
}
func getDirectoryFiles() -> String {
return self.directoryFiles
}
func selectFolder() {
self.directoryFiles = "Test"
}
var body: some View {
Button(action: {
self.directoryFiles = "Test"
}) {
Text("Select Folder")
}
}
}
struct HomeContentView: View {
let filemanager = FileManagerView(directoryFiles: "")
var body: some View {
VStack {
Text("Select a file directory to generate photo albums from.")
.padding(5)
.multilineTextAlignment(.center)
if (filemanager.getDirectoryFiles() == "") {
filemanager
} else if (filemanager.getDirectoryFiles() == "Test") {
Text("Test is selected")
} else {
Text(filemanager.getDirectoryFiles())
}
}
}
}
#Preview {
HomeContentView()
}
Okay so hopefully you managed to get this to work using a binding on your own. Here is my solution to compare it to:
You should read this amazing article on passing data between views in SwiftUI. It's all you'll ever need: https://www.vadimbulavin.com/passing-data-between-swiftui-views/
In summary:
@Environment
@Binding
and CallbacksPreferenceKey
@State
property)The reason why your view wasn't updating earlier was because SwiftUI only finds out when the value of properties have changed. So using the return value of a function like
wouldn't trigger an update as those aren't properties. Best of luck learning Swift!