我想在我的视图中检测一个鼠标向下和一个鼠标向上事件(一个简单的矩形(。这是我已经做的代码。不幸的是,我在控制台上有很多"鼠标向下"one_answers"鼠标向上"。这不是我想要的。当鼠标按下我的矩形时,我只想要一个"鼠标向下",当鼠标释放时,我想要一个"鼠标向上"。
var body: some View {
Rectangle()
.onAppear(perform: {
NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown]) { event in
print ("mouse down")
return event
}
NSEvent.addLocalMonitorForEvents(matching: [.leftMouseUp]) { event in
print ("mouse up")
return event
}
})
}
我使用View修饰符找到了解决方案
//
// ContentView.swift
// OnPressedOnRelease
//
import SwiftUI
struct ContentView: View {
@State private var message: String = "Click on rectangle"
var body: some View {
VStack {
Image(systemName: "magicmouse")
.imageScale(.large)
.foregroundColor(.accentColor)
Text("(message)")
Rectangle()
.modifier(PressActions(
onPress: {
// Do something on press...
message = "Mouse down"
},
onRelease: {
// Do something on release...
message = "Mouse up"
}
))
}
.padding()
.frame(width: 200, height: 200)
}
}
struct PressActions: ViewModifier {
var onPress: () -> Void
var onRelease: () -> Void
func body(content: Content) -> some View {
content
.simultaneousGesture(
DragGesture(minimumDistance: 0)
.onChanged({ _ in
onPress()
})
.onEnded({ _ in
onRelease()
})
)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
我最近使用过Gestures,一个很好的解决方案就是这样做:
struct ContentView: View {
@State var dragGestureValue: DragGesture.Value?
var body: some View {
Rectangle()
.gesture(pressActionsGesture())
.padding()
}
private func pressActionsGesture() -> some Gesture {
return DragGesture(minimumDistance: 0)
.onChanged {
// If nil, it means its the beginning of the DragGesture
if dragGestureValue == nil {
print("Mouse Down")
}
// Gives DragGesture informations to our @State value
dragGestureValue = $0
}
.onEnded { _ in
print("Mouse Up")
dragGestureValue = nil
}
}
}