@State var 在视图外更改值时不会更新

时间:2021-04-06 17:01:53

标签: xcode swiftui

如果我想使用 $checkBox 在视图中使用它,我需要使用“@State”声明 checkBox 数组并且它工作正常但是当我想更新切换(数组的 1 个或多个元素)时视图之外的函数,数组不会更新。我尝试使用 @Binding 和 @Published 声明它,但没有成功。我看到了很多类似的问答,但我没有找到适合我的案例的解决方案。这是我的代码:

struct CheckboxStyle: ToggleStyle {
    func makeBody(configuration: Self.Configuration) -> some View {
        return HStack {
            Image(systemName: configuration.isOn ? "checkmark.circle.fill" : "circle")
                .resizable()
                .frame(width: 24, height: 24)
                .foregroundColor(configuration.isOn ? .green : .gray)
                .onTapGesture { configuration.isOn.toggle() }
            configuration.label
        }
    }
}

struct ContentView: View {
    @State var checkBox = Array(repeating: false, count: 14)
    let checkBoxName: [LocalizedStringKey] = ["checkPressure", "checkVisibility", "checkCloudCover", "checkAirTemp", "checkWaterTemp", "checkWindDir", "checkWindSpeed", "checkWindGust", "checkCurrentDir", "checkCurrentSpeed", "checkSwellDir", "checkWaveHeight", "checkWavePeriod", "checkTideHeight"]
    
    var body: some View {
        ScrollView {
            VStack(alignment: .leading) {
                Group {
                    ForEach(0..<7) { t in
                        Toggle(isOn: $checkBox[t], label: {
                            Text(checkBoxName[t]).font(.footnote).fontWeight(.light)
                        }).toggleStyle(CheckboxStyle()).padding(5)
                    }
                }
                Group {
                    ForEach(7..<14) { t in
                        Toggle(isOn: $checkBox[t], label: {
                            Text(checkBoxName[t]).font(.footnote).fontWeight(.light)
                        }).toggleStyle(CheckboxStyle()).padding(5)
                    }
                }
            }
        }
    }
}

感谢帮助

0 个答案:

没有答案