fix(macos): remove monitor after use

This commit is contained in:
Shibo Lyu 2024-12-18 15:49:02 +08:00
parent 246b20d079
commit 6b33bcdbe4

View file

@ -27,7 +27,8 @@ struct UnderlyingImageView: View {
@State private var tempRotation: Angle = .zero @State private var tempRotation: Angle = .zero
@State private var scrolling: Bool = false @State private var scrolling: Bool = false
#if os(macOS) #if os(macOS)
@State private var isHovering: Bool = false @State private var hovering: Bool = false
@State private var scrollMonitor: Any?
#endif #endif
// When rotated odd multiples of 90 degrees, we need to switch width and height of the image in calculations. // When rotated odd multiples of 90 degrees, we need to switch width and height of the image in calculations.
@ -91,18 +92,24 @@ struct UnderlyingImageView: View {
scale = min(widthScale, heightScale) scale = min(widthScale, heightScale)
} }
private func setupScrollMonitor() {
#if os(macOS) #if os(macOS)
NSEvent.addLocalMonitorForEvents(matching: .scrollWheel) {event in private func setupScrollMonitor() {
if isHovering { scrollMonitor = NSEvent.addLocalMonitorForEvents(matching: .scrollWheel) { event in
if hovering {
scrolling = true scrolling = true
scale = scale + event.scrollingDeltaY / 1000 scale = scale + event.scrollingDeltaY / 1000
} }
return event return event
} }
#endif
} }
private func removeScrollMonitor() {
if let scrollMonitor {
NSEvent.removeMonitor(scrollMonitor)
}
}
#endif
var imageView: Image { var imageView: Image {
#if os(macOS) #if os(macOS)
Image(nsImage: image) Image(nsImage: image)
@ -116,9 +123,14 @@ struct UnderlyingImageView: View {
.gesture(dragGesture) .gesture(dragGesture)
.gesture(magnificationgesture) .gesture(magnificationgesture)
.gesture(rotationGesture) .gesture(rotationGesture)
#if os(macOS)
.onAppear { .onAppear {
setupScrollMonitor() setupScrollMonitor()
} }
.onDisappear {
removeScrollMonitor()
}
#endif
} }
var dragGesture: some Gesture { var dragGesture: some Gesture {
@ -174,9 +186,7 @@ struct UnderlyingImageView: View {
adjustToFulfillTargetFrame() adjustToFulfillTargetFrame()
} }
#if os(macOS) #if os(macOS)
.onHover { hovering in .onHover { hovering = $0 }
isHovering = hovering
}
#endif #endif
} }
} }