【问题标题】:How can I change a global variable's value from inside a function?如何从函数内部更改全局变量的值?
【发布时间】:2021-03-12 12:22:48
【问题描述】:

我在struct 内的代码中有一个@State 布尔值,我有一个toggle()s 按钮。但是,我也想在我的其他视图中使用该变量。所以我需要把它放在struct 外面,这样我就可以在其他地方使用它了。我的问题是我现在如何改变它的价值?以前我的button 的操作toggled 它。现在怎么改?

这是我的代码:

struct ContentView: View {
    @State var checked: Bool = false
    var body: some View {
     HStack {
            Button(action: {checked.toggle()}) {
                Image(systemName: checked ? "checkmark.square": "square")
                .resizable()
                .aspectRatio(contentMode: .fit)
                .scaledToFit()
                .foregroundColor(.black)
                .frame(height: 20)
            }
            Text("I agree")
            .fontWeight(.bold)
            Spacer()
        }
        .padding(.horizontal, 20)
    }
}

但是,我希望它工作

var checked:Bool = false
struct ContentView: View {
    var body: some View {
     HStack {
            Button(action: {checked.toggle()}) {
                Image(systemName: checked ? "checkmark.square": "square")
                .resizable()
                .aspectRatio(contentMode: .fit)
                .scaledToFit()
                .foregroundColor(.black)
                .frame(height: 20)
            }
            Text("I agree")
            .fontWeight(.bold)
            Spacer()
        }
        .padding(.horizontal, 20)
    }
}

【问题讨论】:

  • 你会为此展示你的代码吗?
  • 我确实分享了它。

标签: ios swift if-statement swiftui boolean


【解决方案1】:

可能的解决方案是使用包装了这个属性的共享可观察对象,然后它可以在所有依赖视图中观察。

这是一个演示。使用 Xcode 12.1 / iOS 14.1 测试

class GlobalState: ObservableObject {
    static let shared = GlobalState()
    
    @Published var checked:Bool = false
}

struct myView: View {
    @ObservedObject var gs = GlobalState.shared
    
    var body: some View {
        HStack {
            Button(action: {gs.checked.toggle()}) {
                Image(systemName: gs.checked ? "checkmark.square": "square")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .scaledToFit()
                    .foregroundColor(.black)
                    .frame(height: 20)
            }
            Text("I agree")
                .fontWeight(.bold)
            Spacer()
        }
        .padding(.horizontal, 20)
        Spacer()
    }
}

【讨论】:

  • class ViewRouter: ObservableObject { @ObservedObject var globalState = GlobalState.shared init() { if UserDefaults.standard.bool(forKey: "didLaunchBefore") && globalState.checked{ //Agreement s checked in OnBoardingView currentPage = "appView" } else { UserDefaults.standard.set(true, forKey: "didLaunchBefore") currentPage = "onboardingView" } } @Published var currentPage: String }
  • 感谢它的工作,但是当我将它添加到这个类时,我得到了错误。
  • 'self' 在所有成员初始化之前被闭包捕获
猜你喜欢
  • 2013-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多