Let’s imagine HStack
full of views. You put down your finger on the leftmost view and lift it up on the rightmost one. What modifier to use for the views in-betweeen just to be notified when the finger is sliding over them? With mouse it would be onHover, but with finger is there anything?
Without a modifier, the result can be achieved with this code:
import SwiftUI
import PlaygroundSupport
//
// How to refactor this ugly code
// with a modifier similar to onHover(perform:)?
//
struct ContentView: View{
@State var isHovered = Array(repeating: false, count: 8)
@State private var location = CGPoint.zero
var body: some View{
HStack{
ForEach(0..<8){ i in
GeometryReader{ g in
Rectangle()
.fill(isHovered[i] ? .orange : .gray)
.onChange(of: location) { newValue in
isHovered[i] = g.frame(
in: .named("keyboardSpace")
).contains(location)
}
}
}
}
.gesture(
DragGesture()
.onChanged { gesture in
location = gesture.location
}
.onEnded{ _ in
isHovered = Array(repeating: false, count: 8)
}
)
.frame(width: 500, height: 500)
.coordinateSpace(name: "keyboardSpace")
}
}
PlaygroundPage.current.setLiveView(ContentView())