Let's say I had some code that would allow a user to switch between "pages" and keep track of the last view shown and the number of taps made on each page:
enum ViewRouter: Int {
case alpha, beta
}
struct Tapper: View {
@Binding var count: Int
var body: some View {
Button("Tap me to ⬆️ value", action: {
count += 1})
Text("This page's tap total = \(count)")
Button("Clear", action: {
count = 0})
}
}
struct HomeView: View {
@AppStorage("screen") var currentView: ViewRouter = ViewRouter.alpha
var body: some View {
VStack {
if currentView == ViewRouter.alpha {
Page1(viewSwitcher: $currentView)
} else {
Page2(viewSwitcher: $currentView)
}}}}
struct Page1: View {
@Binding var viewSwitcher: ViewRouter
@AppStorage("tapsForPage1") var tapCount: Int = 0
var body: some View {
Text("Page \(viewSwitcher.rawValue + 1)").font(.title)
Button("➡️ 2", action: {
viewSwitcher = ViewRouter.beta})
Tapper(count: $tapCount)
}
}
struct Page2: View {
@Binding var viewSwitcher: ViewRouter
@AppStorage("tapsForPage2") var tapCount: Int = 0
var body: some View {
Text("Page \(viewSwitcher.rawValue + 1)").font(.title)
Button("➡️ 1", action: {
viewSwitcher = ViewRouter.alpha})
Tapper(count: $tapCount)
}
}
Using the keys "TapsForPage1"
for Page1
and "TapsForPage2"
for Page2
are fine when there are just 2 pages, but what if there were 100 pages, and I'd be setting things up with a single struct
named Page
with each one having a pageNumber
property, e.g.,
struct Page: View {
@Binding var viewSwitcher: ViewRouter
@Binding var pageNumber: Int
@AppStorage("tapsForPageX") var tapCount: Int = 0
var body: some View {
Text("Page \(viewSwitcher.rawValue + 1)").font(.title)
...
Tapper(count: $tapCount)
}
}
Is there a way to say "I want the key for each Page
's @AppStorage
(or @SceneStorage
?) wrapper to be "tapsForPage\(pageNumber)"
?" Is this even the correct method for going about doing what I'm attempting?