I have a simple app that is intended to work like this:
- App loads with a default image
- Once a tap is received a random image is loaded from list
- If no tap is received for 5 seconds we reset back to default image
I'm attempting to accomplish this using DispatchQueue and DispatchWorkItem. I have managed to get the above functionality working - except when a user is tapping multiple times.
I'm assuming this is because we are initiating the "resetToOff" DispatchWorkItem each time we tap without resetting the 5 seconds.
How do I reset the image back to the default image if there is no touch received for 5 seconds while resetting the DispatchQueue?
Here is what I have so far:
import SwiftUI
struct PlayView : View {
@ObservedObject var viewRouter: ViewRouter
@State var imageName : String = "smiley"
var body: some View {
ZStack {
Color.black
.edgesIgnoringSafeArea(.all)
Image(imageName)
}
.gesture(
TapGesture()
.onEnded {
let resetToOff = DispatchWorkItem {
self.imageName = "smiley"
}
self.changeImage()
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(5), execute: resetToOff)
}
)
// Activate the options menu
.onLongPressGesture(minimumDuration: 3) {
self.viewRouter.currentPage = "menuView"
}
}
func changeImage() {
let tempImageName : String = self.imageName
let list : Array = [
"smileyPink",
"smileyGreen",
"smileyRed",
"smileyBlue",
"smileyYellow"
]
self.imageName = list.randomElement() ?? ""
// Ensure that new image selection is not the same as previous image
while tempImageName == self.imageName {
self.imageName = list.randomElement() ?? ""
}
}
}
struct PlayView_Previews : PreviewProvider {
static var previews: some View {
PlayView(viewRouter: ViewRouter())
}
}
Any help with this would be much appreciated.