This is my first question on stackoverflow and I started working with iOS, Swift and SwiftUI only a month ago. Please be understanding and tell me if I did something wrong.
I would like to determine if a String changed within a struct that has a bound String(@Binding) to it. I copy the original String to a second string on start (within body). Both Strings are always the same, as if the reference was copied, instead of the value. As far as I understood the documentation on String a String is always copied using its value. Please correct me if I am wrong. Here is some example code:
struct EditTextSheet: View {
var title: String
@Binding var showSheetView: Bool
@Binding var userConfirmedChange: Bool
@Binding var textToEdit: String
var body: some View
{
// use to determine if user made any changes to text
let originalText: String = textToEdit
NavigationView
{
Form
{
Section(header: Text(title))
{
TextField(textToEdit, text: $textToEdit)
}
}
.navigationBarTitle("", displayMode: .inline)
// buttons within navigation Bar OK top right, cancel top left. OK also sets userConfirmedChange to true
// Cancel BUTTON
.navigationBarItems(leading: Button(action: {
self.showSheetView = false
}) {
Text("Cancel")
}, trailing: Button(action: {
// OK BUTTON
if textToEdit.isEmpty
{
// tell user that String cannot be empty
...
}
else
{
// ***BELOW IS ALWAYS THE SAME***
// if "Test" was passed as textToEdit and user then
// changes textToEdit via the TextField to "Test1234"
// below if clause results in "Test1234" == "Test1234"
// what I want is "Test" == "Test1234"
if textToEdit == originalText
{
self.userConfirmedChange = false
self.showSheetView = false
}
else
{
self.userConfirmedChange = true
self.showSheetView = false
}
}
}) {
Text("OK")
.bold()
})
}
}
}
this struct is a sheet, that gets called like this:
...
@State var showEditSheet = false
@State var userConfirmedChange = false
@State var editText: String = ""
...
Button(action: {
editText = "Test"
userConfirmedChange = false
showEditSheet.toggle()
}) {
Text ("Edit Test")
}.sheet(isPresented: $showEditSheet, onDismiss: {
if userConfirmedChange
{
print("\(editText)")
}
else
{
print("cancelled")
}
}) {
EditTextSheet(title: "some title", showSheetView: $showEditSheet, userConfirmedChange: $userConfirmedChange, textToEdit: $editText)
}
...