I'm a beginner at iOS development and I'm currently making an app which is a sort of PDF viewer. I want it to have three different views, the main document view, a table of contents view and a search view and I want to navigate between them using a toolbar at the bottom. I have currently implemented this in the following manner:
@State private var destinationView: AnyView = AnyView(DocumentView())
var body: some View {
destinationView
.toolbar(content: {
ToolbarItem(placement: .bottomBar) {
Spacer()
}
ToolbarItem(placement: .bottomBar) {
Button(action: { destinationView = AnyView(ContentView()) }) {
Image(systemName: "list.dash")
}
}
ToolbarItem(placement: .bottomBar) {
Spacer()
}
ToolbarItem(placement: .bottomBar) {
Button(action: { destinationView = AnyView(DocumentView()) }) {
Image(systemName: "doc.richtext")
}
}
ToolbarItem(placement: .bottomBar) {
Spacer()
}
ToolbarItem(placement: .bottomBar) {
Button(action: { destinationView = AnyView(SearchView()) }) {
Image(systemName: "magnifyingglass")
}
}
ToolbarItem(placement: .bottomBar) {
Spacer()
}
})
}
This works fine for the most part but has some problems.
The first, and biggest problem is that whenever I switch to a view using this approach, the view seems to get reinitialized. Say for example I'm in the search view where I search for a word and get a bunch of results. If I then go to the document view and then back to the search view, my search word and all of the search results are gone. How do I solve this? Maybe this also relates to a bigger question. How do I go about resource management? Some of these views load quite large files, should I have some type of monolithic resource manager somewhere that loads these files on app startup or how do I manage that?
The second problem is that the toolbar doesn't seem to take precedence above the underlying elements. For example, if I'm in the search view and I have a bunch of search results in my scroll view, when I press a button on the toolbar, the search result beneath the toolbar also seems to get pressed. This causes the toolbar to not trigger its button action, making it hard to escape the search view.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…