I'm trying to scale the `view`(zoom in and out) when the user scroll from the mouse after hovering the view. So, since I want to track scroll event across the application, I placed the following code in the root. But I don't know how to use it in the view.
**View**
import SwiftUI
struct ContentView: View {
@State var recColour: Color = .black
@State var scaleby = 2.0
var body: some View {
VStack (alignment: .leading){
ZStack {
Rectangle()
.fill(.gray)
.frame(width: 100, height: 100)
}
}
.scaleEffect(scaleby)
.onTapGesture {
withAnimation {scaleby += 1}
}
}
}
**The root with scroll event detector**
import SwiftUI
import Combine
@main
struct tempApp: App {
@State var subs = Set<AnyCancellable>()
@SceneBuilder
var body: some Scene {
WindowGroup {
ContentView()
.onAppear { trackScrollWheel() }
}
}
}
extension tempApp {
func trackScrollWheel() {
NSApp.publisher(for: \.currentEvent)
.filter { event in event?.type == .scrollWheel }
.throttle(for: .milliseconds(200),
scheduler: DispatchQueue.main,
latest: true)
.sink {
if let event = $0 {
if event.deltaX > 0 { print("right") }
if event.deltaX < 0 { print("left") }
if event.deltaY > 0 { print("down") }
if event.deltaY < 0 { print("up") }
}
}
.store(in: &subs)
}
}
相似问题