首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >How to track the mouse scroll event?

How to track the mouse scroll event?

提问于 2023-05-04 13:15:46
回答 0关注 0查看 54

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**

代码语言:js
复制
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**

代码语言:js
复制
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)
    }
}

回答

和开发者交流更多问题细节吧,去 写回答
相关文章

相似问题

相关问答用户
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档