I am doing an app that lists some photos. When the user taps a photo, a sheet appears with the selected photo.
The problem is: Sometimes I tap on the second photo, i. e., index = 1, and the first photo appears on the Sheet View. I don't know why, but the problem should also happen with other indices but until now only with the second photo. Here is my code:
import SwiftUI
struct SheetView: View {
@Binding var photo: String
var body: some View {
Text("photo title: " + photo)
}
}
struct ContentView: View {
@State private var selectedIndex: Int = 0
@State private var photoEdition: Bool = false
@State var photos: [String] = ["gigio", "lulu", "lucky"]
private var photoToEdit: Binding<String> {
.init(get: { () -> String in
print("get", photos[selectedIndex], selectedIndex)
return photos[selectedIndex]
},
set: { (newValue) in
photos[selectedIndex] = newValue
print("set", photos[selectedIndex], selectedIndex)
})
}
var body: some View {
VStack {
ForEach(photos.indices, id:\.self) { index in
Button(action: {
photoTapHandler(selectedIndex: index)
}) {
Text(photos[index]).padding(10)
}
}
} .sheet(isPresented: $photoEdition, content: {
SheetView(photo: photoToEdit)
})
}
private func photoTapHandler(selectedIndex: Int) {
print("updating selected index to ", selectedIndex)
self.selectedIndex = selectedIndex
self.photoEdition = true
}
}
I think what is happening is that on the photoTapHandler
function, the variable photoEdition
is set to true before selectedIndex
is changed. Any idea why? Here is the execution logs.
updating selected index to 1
get gigio 0
get gigio 0
By replacing the body with the following, I don't get the error.
var body: some View {
VStack {
ForEach(photos.indices, id:\.self) { index in
Button(action: {
photoTapHandler(selectedIndex: index)
}) {
Text(photos[index]).padding(10)
}
}
}.onChange(of: selectedIndex) { selectedIndex in
self.photoEdition = true
}
.sheet(isPresented: $photoEdition, content: {
SheetView(photo: photoToEdit)
})
}
private func photoTapHandler(selectedIndex: Int) {
print("updating selected index to ", selectedIndex)
self.selectedIndex = selectedIndex
// self.photoEdition = true
}
Thank you all in advance! :)