在用户登录时将切换添加到列表SwiftUI并保存切换状态

时间:2020-06-16 01:41:12

标签: swift swiftui swiftui-list

我正在尝试向列表视图添加一个切换开关,以打开或关闭位置信息。我还想知道如何在用户退出之前保持切换状态。谢谢任何可以帮助我的人。我不想向其中添加任何位置功能,但我只想准备好占位符。

这是我的代码;

import SwiftUI

    struct SettingsView: View {

@State private var notificationToggle : Bool = false
@State private var locationToggle : Bool = false
@Environment(\.colorScheme) var colorScheme

var body: some View {

    List{

        Section {

                NavigationLink(destination: SettingsAccountView()) {

                    Button(action: {
                        print("Account Settings")
                    }) {
                        SettingsCell(title: "Account", imgName: "person.crop.circle", clr: Color("Freshness"))
                    }

                }

                Toggle(isOn: $locationToggle {
                    print("locationToggled")
            }) {
                       SettingsCell(title: "Location", imgName: "location", clr: Color("Freshness"))
                    }

                NavigationLink(destination: SettingsNotificationsView()) {

                    Button(action: {
                        print("Notification Settings")
                    }) {
                        SettingsCell(title: "Notifications", imgName: "bell", clr: Color("Freshness"))
                    }
                }
        }

        Section {

                NavigationLink(destination: SettingsAboutView()) {

                    Button(action: {
                        print("About")
                    }) {
                        SettingsCell(title: "About", imgName: "info.circle.fill", clr: Color("ShipsOfficer").opacity(0.3))
                    }
                }
        }

    }.listStyle(GroupedListStyle())
    .environment(\.horizontalSizeClass, .regular)
    .navigationBarTitle("Settings", displayMode: .inline)
}

}

2 个答案:

答案 0 :(得分:1)

您始终可以这样用UserDefaults保存本地数据:

let defaults = UserDefaults.standard
defaults.set("On", forKey: "toggleStatus")

用户注销后,您可以:

defaults.removeObjectForKey("toggleStatus")

答案 1 :(得分:0)

由于您要在切换时保存切换状态并在出现r.config(text="Result =" + str(round(c, 2))) 时检索它,因此只需添加View手势来存储,并添加onTap动作块即可从{中检索切换状态{1}}。这是您实现此目标的方法:

onAppear