I save the state from the toggle in a UserDefault. But I dont know how to write that the toggle is turning on or off when the view appears.
HStack {
Toggle(isOn: $isOnorOff) {
Text(isOnorOff ? "ON" : "OFF")
}
.animation(.easeInOut)
}
.onTapGesture {
self.isOnorOff.toggle()
self.test()
}
}
}
.onAppear {
// Turn the toggle on or off with UserDefaults
}
func test(){
var onoff = isOnorOff ? "on" : "off"
let defaults = UserDefaults()
defaults.set(onoff, forKey: "onOrOff")
print(defaults.object(forKey: "onOrOff"))
}
Retrieve the value from UserDefaults
.onAppear {
isOnorOff = UserDefaults.standard.string(forKey: "onOrOff") == "on"
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.