@Appstorage 未根据我的选择器选择进行更新 - SwiftUI - WatchApp

@Appstorage is not updating based on my picker selection - SwiftUI - WatchApp

我有一个更新变量 bmr 的选择器。 选择器不更新值。我在第二个屏幕上放了一个测试文本,看看我是否可以调用新值,它总是显示默认值。

import SwiftUI

struct ProfileView: View {
    
    @AppStorage("ProfileView") var profileView:Bool = false
    @AppStorage("ContentView") var contentView:Bool = false
    @AppStorage("TimerView") var timerView:Bool = false
    @AppStorage("Name") var userName: String?
    @AppStorage("BMR") var bmr: Int?
    
    var body: some View {
        VStack {
            Picker(selection: $bmr, label: Text("Enter your BMR:")) {
                Text("50").tag(50)
                Text("60").tag(60)
                Text("70").tag(70)
                Text("80").tag(80)
            }
            NavigationLink(destination: ContentView()) {
                Text("Save")
            }
            
        }
    }
}

struct ContentView: View {
    
    @AppStorage("ProfileView") var profileView:Bool = false
    @AppStorage("ContentView") var contentView:Bool = false
    @AppStorage("TimerView") var timerView:Bool = false
    @AppStorage("Name") var userName: String?
    @AppStorage("BMR") var bmr: Int?
    
    var body: some View {
        VStack {
            Text("Your BMR: \(bmr ?? 50)")
            }
    }
    }

我正在学习,所以我不知道该尝试什么。我尝试了绑定和解除绑定,它并没有真正起作用。

我之前尝试存储变量并传递视图以测试它是否会更新,并且工作正常。但是通过视图传递信息不适用于我的应用程序,因为即使我退出,我也需要存储这些数据。

问题是 bmrInt? 而您的标签是 Int。因为它们不是一回事,所以选择不会更新它。诀窍是将您的标签转换为 Int?,如下所示:

struct ProfileView: View {
    
    @AppStorage("ProfileView") var profileView:Bool = false
    @AppStorage("ContentView") var contentView:Bool = false
    @AppStorage("TimerView") var timerView:Bool = false
    @AppStorage("Name") var userName: String?
    @AppStorage("BMR") var bmr: Int?
    
    var body: some View {
        VStack {
            Picker(selection: $bmr, label: Text("Enter your BMR:")) {
                Text("50").tag(50 as Int?)
                Text("60").tag(60 as Int?)
                Text("70").tag(70 as Int?)
                Text("80").tag(80 as Int?)
            }
            NavigationLink(destination: ContentView()) {
                Text("Save")
            }
            
        }
    }
}

标签和选择类型必须完全匹配。