SwiftUI Stepper save value - swiftui

How can I save the value of the stepper in the UserDefaults every time I press + or -?
I don't want a separate save button.
struct Settings: View {
#State private var zielwert = UserDefaults.standard.integer(forKey: "zielwert")
var body: some View {
VStack {
Stepper("Zielwert \(zielwert)", value: $zielwert, in: 90...160)
Button("Speichern") {
UserDefaults.standard.set(self.zielwert, forKey: "zielwert")
}
}
.padding(.horizontal, 23.0)
}
}

SwiftUI 2
Use AppStorage:
struct Settings: View {
#AppStorage("zielwert") private var zielwert = 90
var body: some View {
VStack {
Stepper("Zielwert \(zielwert)", value: $zielwert, in: 90...160)
}
.padding(.horizontal, 23.0)
}
}
SwiftUI 1
Use .onReceive:
import Combine
struct Settings: View {
#State private var zielwert = UserDefaults.standard.integer(forKey: "zielwert")
var body: some View {
VStack {
Stepper("Zielwert \(zielwert)", value: $zielwert, in: 90...160)
.onReceive(Just(zielwert)) { zielwert in
print(zielwert)
UserDefaults.standard.set(zielwert, forKey: "zielwert")
}
}
.padding(.horizontal, 23.0)
}
}

Related

My environmentObject isn't working.I tap on navigationLink and see nothing in there

My environmentObject isn't working.I tap on navigationLink and see nothing in there.
I change note but it does not get updated.I made viewModel and share data from it everywhere I need it
I made the second TextEditor to do changes to my notes, but I cannot see changes.I just want to write smith and data should be updated
So how can I fix that?
import SwiftUI
#main
struct WhatToDoAppApp: App {
#StateObject private var vm = NoteViewModel()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(vm)
}
}
}
//ContentView.swift
import SwiftUI
struct ContentView: View {
#EnvironmentObject var vm: NoteViewModel
#State private var showSheet = false
#State private var searchText = ""
var body: some View {
NavigationView {
List {
ForEach(vm.notes) { item in
NavigationLink(destination: NoteDetailView()) {
Text(item.task)
.lineLimit(1)
}
}
.onDelete(perform: vm.deleteTask)
.onMove(perform: vm.moveTask)
}
.searchable(text: $searchText) {
if !searchResult.isEmpty {
ForEach(searchResult) { item in
NavigationLink(destination: NoteDetailView()) {
Text(item.task)
.lineLimit(1)
}
}
}
}
.navigationBarTitle("Notes")
.safeAreaInset(edge: .bottom) {
Color.clear
.frame(maxHeight: 40)
.background(.gray.opacity(0.7))
HStack {
Spacer(minLength: 160)
Text("\(vm.notes.count) notes")
.foregroundColor(.black.opacity(0.3))
Spacer()
Button {
showSheet = true
} label: {
Image(systemName: "square")
.font(.largeTitle)
.padding(.trailing)
}
}
}
.sheet(isPresented: $showSheet) {
NoteView()
}
}
}
var searchResult: [ToDoItem] {
guard !searchText.isEmpty else { return vm.notes }
return vm.notes.filter { $0.task.contains(searchText) }
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
Group {
ContentView()
.preferredColorScheme(.dark)
ContentView()
.preferredColorScheme(.light)
}
.environmentObject(NoteViewModel())
}
}
//NoteDetailView.swift
import SwiftUI
struct NoteDetailView: View {
#EnvironmentObject var vm: NoteViewModel
var body: some View {
VStack {
TextEditor(text: $vm.text)
Spacer()
}
}
}
struct NotedetailView_Previews: PreviewProvider {
static var previews: some View {
NoteDetailView().environmentObject(NoteViewModel())
}
}
//NoteView.swift
import SwiftUI
struct NoteView: View {
// #State private var text = ""
#EnvironmentObject var vm: NoteViewModel
#Environment(\.dismiss) var dismiss
var body: some View {
NavigationView {
VStack {
TextEditor(text: $vm.text)
}
.padding()
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: {
addTask()
dismiss()
vm.text = ""
}, label: {
Text("Done")
.font(.system(size: 25))
.foregroundColor(.accentColor)
})
}
}
}
}
func addTask() {
vm.add(ToDoItem(task: vm.text))
}
}
struct NoteView_Previews: PreviewProvider {
static var previews: some View {
NoteView()
.environmentObject(NoteViewModel())
}
}
import Foundation
struct ToDoItem: Identifiable, Codable {
var id = UUID()
var task : String
}
class NoteViewModel: ObservableObject {
#Published var notes = [ToDoItem]()
#Published var text = ""
let saveKey = "SavedKey"
init() {
if let data = UserDefaults.standard.data(forKey: saveKey) {
if let decoded = try? JSONDecoder().decode([ToDoItem].self, from: data) {
notes = decoded
return
}
}
notes = []
}
private func save() {
if let encoded = try? JSONEncoder().encode(notes) {
UserDefaults.standard.set(encoded, forKey: saveKey)
}
}
func add(_ note: ToDoItem) {
notes.append(note)
save()
}
func deleteTask(indexSet: IndexSet) {
indexSet.forEach { index in
self.notes.remove(at: index)
save()
}
}
}
The detail view should be a #Binding, and you can use the array that you have in the viewModel as an Bindable List here the fixes:
List {
ForEach($vm.notes) { $item in
NavigationLink(item.task, destination: NoteDetailView(note: $item))
}
The detail view should look like this:
struct NoteDetailView: View {
#Binding var note: ToDoItem
#EnvironmentObject var vm: NoteViewModel
var body: some View {
VStack {
TextEditor(text: $note.task)
Spacer()
}
.onDisappear {
vm.save()
}
}}
This way every time the user updates and closes the modal, the list will be saved.

How to observe updates in binded values SwiftUI

I'm not sure if I created my custom TextField properly, because I am unable to observe the value changes to an #Binded text. Running the following code, you may observe that print(text) is not executed when you manually enter text into the text field.
import SwiftUI
#main
struct TestOutWeirdTextFieldApp: App {
#State var text: String = "" {
didSet {
print(text)
}
}
var body: some Scene {
WindowGroup {
StandardTextField(placeholderText: "Enter text", defaultText: $text)
}
}
}
struct StandardTextField: View {
#State var placeholderText: String {
didSet {
print(#line)
print(placeholderText)
}
}
#Binding var defaultText: String {
didSet {
print(#line)
print(defaultText)
}
}
#State var systemImage: String?
#State var underlineColor: Color = .accentColor
#State var edges: Edge.Set = .all
#State var length: CGFloat? = nil
#State var secure: Bool = false
var body: some View {
HStack {
if secure {
SecureField(placeholderText, text: $defaultText)
.foregroundColor(underlineColor)
} else {
TextField(placeholderText, text: $defaultText)
.foregroundColor(underlineColor)
}
if let systemImage = systemImage {
Image(systemName: systemImage)
.foregroundColor(.white)
}
}
.overlay(
Rectangle()
.frame(height: 2)
.padding(.top, 35)
)
.foregroundColor(underlineColor)
.padding(edges, length)
}
}
struct StandardTextView_Previews: PreviewProvider {
static var previews: some View {
StandardTextField(placeholderText: "Placement text", defaultText: .constant("")).previewLayout(.sizeThatFits)
}
}
Instead of didSet you need to use .onChange(of: modifier, like
HStack {
// ... your code here
}
.onChange(of: defaultText) { print($0) } // << this !!
.overlay(

ContentView redraw from change in modalView not triggered

Ever since the advent of swiftUI 2.0, I have been unable to update a view according to a change done in another modally-presented view (the settings view).
I display a string on my main ContentView that derives its content from a segmented Picker value on the SettingsView.
The problem is that after the user changes the setting and discards the SettingsView, the string in ContentView is not updated. The body is not redrawn.
I am making use of #ObservableObject and #StateObject so every change to it should trigger a redraw, but I can't make it work...
I created a class that conforms to the ObservableObject protocol : AppState
I am using that class to try and pass data and -more importantly- data changes between the views in order to have my ContentView redrawn according to the the user's settings.
In order to instantiate this class, I registered a single UserDefaults in my AppDelegate file.
I also imported the Combine Framework into my project and added the import Combine line in each and every file !
I've simplified my code as much as possible, in order to illustrate the issue, so the following might seem a bit circumvolutated, but it is derived from a much more complex app, sorry about that.
Here is my ContentView code :
import SwiftUI
import Combine
struct ContentView: View {
#StateObject var appState: AppState
#State var modalViewCaller = 0 // used to present correct modalView
#State var modalIsPresented = false // to present the modal views
var body: some View {
let stringArray = generateString() // func to generate string according to user's pref
let recapString = stringArray[0]
return ZStack {
NavigationView {
VStack {
// MARK: - texts :
VStack {
Text(recapString)
.bold()
.multilineTextAlignment(/*#START_MENU_TOKEN#*/.center/*#END_MENU_TOKEN#*/)
} // end of VStack
.padding()
.overlay(RoundedRectangle(cornerRadius: 10)
.stroke(Color(UIColor.systemBlue), lineWidth: 4))
.padding()
} // END of VStack
.onAppear() {
self.modalViewCaller = 0
print("\n\n*********** Content View onAppear triggered ! ************\n")
}
.navigationBarTitle("DataFun", displayMode: .inline)
.navigationBarItems(leading: (
Button(action: {
self.modalViewCaller = 1 // SettingsView
self.modalIsPresented = true
}
) {
Image(systemName: "gear")
.imageScale(.large)
}
))
} // END of NavigationView
.onAppear() {
self.appState.updateValues()
}
} // End of ZStack
.sheet(isPresented: $modalIsPresented) {
sheetContent(modalViewCaller: $modalViewCaller, appState: AppState())
}
.navigationViewStyle(StackNavigationViewStyle())
}
// MARK: - struct sheetContent() :
struct sheetContent: View {
#Binding var modalViewCaller: Int // Binding to the #State modalViewCaller variable from ContentView
#StateObject var appState: AppState
var body: some View {
if modalViewCaller == 1 { // The settings view is called
SettingsView(appState: AppState())
.navigationViewStyle(StackNavigationViewStyle())
.onDisappear { self.modalViewCaller = 0 }
} else if modalViewCaller == 2 { // the "other view" is called
OtherView()
.navigationViewStyle(StackNavigationViewStyle())
.onDisappear { self.modalViewCaller = 0 }
}
}
} // END of func sheetContent
// MARK: - generateString()
func generateString() -> [String] {
var recapString = "" // The recap string
var myArray = [""]
// We create the recap string :
if UserDefaults.standard.integer(forKey: "rules selection") == 0 { // ICAO
recapString = "User chose LEFT"
} else if UserDefaults.standard.integer(forKey: "rules selection") == 1 { // AF Rules
recapString = "User chose RIGHT"
}
myArray = [recapString]
return myArray
} // End of func generateString()
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(appState: AppState())
}
}
Here is my AppState code :
import Foundation
import SwiftUI
import Combine
class AppState: ObservableObject {
#Published var rulesSelection: Int = UserDefaults.standard.integer(forKey: "rules selection")
func updateValues() { // When the user changes a setting, the UserDefault is updated. Here, we align the AppState's value with what is now in the UserDefaults
self.rulesSelection = UserDefaults.standard.integer(forKey: "rules selection")
print("\nappState value (ruleSelection) updated from Appstate class func \"updateValues")
}
}
Here is my SettingsView code :
import SwiftUI
import Combine
struct SettingsView: View {
#Environment(\.presentationMode) var presentationMode // in order to dismiss the Sheet
#StateObject var appState: AppState
#State private var rulesSelection = UserDefaults.standard.integer(forKey: "rules selection") // 0 is LEFT, 1 is RIGHT
var body: some View {
NavigationView {
VStack {
Spacer()
Text("Choose a setting below")
.padding()
Picker("", selection: $rulesSelection) {
Text("LEFT").tag(0)
Text("RIGHT").tag(1)
}
.pickerStyle(SegmentedPickerStyle())
.padding()
Spacer()
}
.navigationBarItems(
leading:
Button("Done") {
self.saveDefaults() // We set the UserDefaults
self.presentationMode.wrappedValue.dismiss() // This dismisses the view
// self.modalViewCaller = 0
}
) // END of NavBarItems
} // END of NavigationBiew
} // END of body
func saveDefaults() {
UserDefaults.standard.set(rulesSelection, forKey: "rules selection")
self.appState.updateValues() // This is a func from the AppState class that will align the appState's value to the UserDefaults
}
}
struct SettingsView_Previews: PreviewProvider {
static var previews: some View {
SettingsView(appState: AppState())
}
}
And a working project if anyone has the time to check this "live" :
https://github.com/Esowes/dataFun
Thanks for any pointers.
Regards.
Well... it was... in short many changes, so here is complete ContentView.swift with fixes.
Note: you need only one StateObject, and one instance set into it, and you need to have published property of observable object in view otherwise it is not refreshed, and changes in UserDefaults do not refresh view until you use AppStorage, etc.
Verified with Xcode 12.1 / iOS 14.1
import SwiftUI
import Combine
struct ContentView: View {
#StateObject var appState: AppState
#State var modalViewCaller = 0 // used to present correct modalView
#State var modalIsPresented = false // to present the modal views
var body: some View {
return ZStack {
NavigationView {
VStack {
// MARK: - texts :
VStack {
RecapStringView(appState: appState)
} // end of VStack
.padding()
.overlay(RoundedRectangle(cornerRadius: 10)
.stroke(Color(UIColor.systemBlue), lineWidth: 4))
.padding()
} // END of VStack
.onAppear() {
self.modalViewCaller = 0
print("\n\n*********** Content View onAppear triggered ! ************\n")
}
.navigationBarTitle("DataFun", displayMode: .inline)
.navigationBarItems(leading: (
Button(action: {
self.modalViewCaller = 1 // SettingsView
self.modalIsPresented = true
}
) {
Image(systemName: "gear")
.imageScale(.large)
}
))
} // END of NavigationView
.onAppear() {
self.appState.updateValues()
}
} // End of ZStack
.sheet(isPresented: $modalIsPresented) {
sheetContent(modalViewCaller: $modalViewCaller, appState: appState)
}
.navigationViewStyle(StackNavigationViewStyle())
}
// MARK: - struct sheetContent() :
struct sheetContent: View {
#Binding var modalViewCaller: Int // Binding to the #State modalViewCaller variable from ContentView
#ObservedObject var appState: AppState
var body: some View {
if modalViewCaller == 1 { // The settings view is called
SettingsView(appState: appState)
.navigationViewStyle(StackNavigationViewStyle())
.onDisappear { self.modalViewCaller = 0 }
} else if modalViewCaller == 2 { // the "other view" is called
OtherView()
.navigationViewStyle(StackNavigationViewStyle())
.onDisappear { self.modalViewCaller = 0 }
}
}
} // END of func sheetContent
}
struct RecapStringView: View {
#ObservedObject var appState: AppState
var body: some View {
Text("User chose " + "\(appState.rulesSelection == 0 ? "LEFT" : "RIGHT")")
.bold()
.multilineTextAlignment(.center)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(appState: AppState())
}
}

How to display another view from an existing view in SwiftUI

I have an existing view displayed. After displaying that view for 2 seconds, I want to navigate or display another view. The following code does not work.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
UIGraphicsBeginImageContext(self.view.frame.size)
UIImage(named: "ProfileSplashScreen")?.draw(in: self.view.bounds)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
self.view.backgroundColor = UIColor(patternImage: image)
DispatchQueue.main.asyncAfter(deadline: .now()+2.0) {
GameSelectorController()
}
//=====================================================
import SwiftUI
struct GameSelectorController: UIViewController {
var body: some View {
Text(/*#START_MENU_TOKEN#*/"Hello, World!"/*#END_MENU_TOKEN#*/)
}
}
struct GameSelectorController_Previews: PreviewProvider {
static var previews: some View {
GameSelectorController()
}
}
In pure SwiftUI you would do something like this:
struct ContentView: View {
#State private var showFirst = true
var body: some View {
Group {
if showFirst {
StartView()
} else {
SecondView()
}
}
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.showFirst = false
}
}
}
}
struct StartView: View {
var body: some View {
Text("First")
}
}
struct SecondView: View {
var body: some View {
Text("Second")
}
}

How to get the picker in SwiftUI to output the chosen value?

I have a picker in swiftUI that are used to show Units of Measure and convert between them. The picker is displayed correctly, but the values are not selected when choosing one of them.
import SwiftUI
struct ContentView: View {
#State private var originalValue = ""
#State private var originalUnit = ""
#State private var convertedUnit = ""
let lenghtUnits = ["meters", "miles", "yards"]
var convertedValue : Double {
return 0 // for now..
}
var body: some View {
NavigationView {
Form {
Section(header: Text("From:")) {
TextField("Value:", text: $originalValue)
.keyboardType(.decimalPad)
Picker("fromUnit" , selection: $originalUnit) {
ForEach(0 ..< lenghtUnits.count) {
Text("\(self.lenghtUnits[$0])")
}
}
.pickerStyle(SegmentedPickerStyle())
}
Section(header: Text("Result")) {
Text("\(convertedValue)")
}
}
.navigationBarTitle("Convert It")
}
}
}
try this. (added tags to your text and made your selection value an int)
struct ContentView: View {
#State private var originalValue = ""
#State private var originalUnit = 0
#State private var convertedUnit = ""
let lenghtUnits = ["meters", "miles", "yards"]
var convertedValue : Double {
return 0 // for now..
}
var body: some View {
NavigationView {
Form {
Section(header: Text("From:")) {
TextField("Value:", text: $originalValue)
.keyboardType(.decimalPad)
Picker("fromUnit" , selection: $originalUnit) {
ForEach(0 ..< lenghtUnits.count) { index in
Text("\(self.lenghtUnits[index])").tag(index)
}
}
.pickerStyle(SegmentedPickerStyle())
}
Section(header: Text("Result")) {
Text("\(convertedValue)")
}
}
.navigationBarTitle("Convert It")
}
}
}