UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: How to detect a single mouse down event in SwiftUI on macOS

Forums > macOS

I want to detect ONE mouse down and ONE mouse up event on my view (a simple Rectangle). Here is the code I already made. Unfortunately I got a lot of 'mouse down' and 'mouse up' on the console. This not what I want. I want just one 'mouse down' when the mouse is pressed on my rectangle and one 'mouse up' when the mouse is released.

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
                }
            })

            }

    }

4      

I found the solution by using a View modifier


//
//  ContentView.swift
//  OnPressedOnRelease
//
//  Created by Sebastien REMY on 30/10/2022.
//

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()
    }
}

https://github.com/Sebastien-Remy/OnPressedOnRelease

5      

I found also an alternative solution


//  ContentView.swift
//  OnPressedOnRelease
//
//  Created by Sebastien REMY on 30/10/2022.
//

import SwiftUI

struct ContentView: View {
    @State private var message: String = "Click on rectangle"
    @State private var mouseDown = false // For alternative solution only
    var body: some View {
        VStack {
            Image(systemName: "magicmouse")
                .imageScale(.large)
                .foregroundColor(.accentColor)
            Text("\(message)")

            Rectangle()
                .modifier(MouseClickActions(
                    onMouseDown: {
                        // Do something on press...
                        message = "Mouse down"
                    },
                    onMouseUp: {
                        // Do something on release...
                        message = "Mouse up"
                    }
                ))
                Spacer()
            Text("Alternative Solution")
            Text("\(mouseDown ? "Mouse is down" : "Mouse is Up")")
            Rectangle()
                .onLongPressGesture(minimumDuration: 2.5, maximumDistance: .infinity, pressing: { pressing in
                    mouseDown = pressing
                }, perform: {})
        }
        .padding()
        .frame(width: 200, height: 200)
    }
}

struct MouseClickActions: ViewModifier {
    var onMouseDown: () -> Void
    var onMouseUp: () -> Void
    func body(content: Content) -> some View {
        content
            .simultaneousGesture(
                DragGesture(minimumDistance: 0)
                    .onChanged({ _ in
                        onMouseDown()
                    })
                    .onEnded({ _ in
                        onMouseUp()
                    })
            )
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

3      

Thanks for sharing your solution.

3      

I see that you're looking for information on how to detect a single mouse down event in SwiftUI on macOS. This can be relevant for various interactions in a macOS app. Here's an example of how you can achieve this in SwiftUI:

import SwiftUI

struct ContentView: View { @State private var mousePressed = false

var body: some View {
    Text("Mouse is pressed: \(mousePressed ? "Yes" : "No")")
        .onTapGesture {
            // This closure will be called when a mouse click event occurs.
            mousePressed.toggle()
        }
}

}

@main struct YourApp: App { var body: some Scene { WindowGroup { ContentView() } } } In this example, we use the onTapGesture modifier on a Text view to detect clicktester.net] events. When a mouse click occurs, the mousePressed state variable is toggled, and the text will update accordingly. You can customize this behavior as needed for your specific use case. clicktester.net

3      

In SwiftUI for macOS, you can detect a single mouse down event using the .onMouseDown modifier. This modifier allows you to attach an action to a view that triggers when a mouse-down event occurs. Here's how to do it:

swift

import SwiftUI

struct ContentView: View { var body: some View { Text("Click Me") .onMouseDown { event in // Handle the mouse down event here print("Mouse down event detected.") } } }

@main struct YourApp: App { var body: some Scene { WindowGroup { ContentView() } } } In this example, we have a simple Text view with the text "Click Me." We use the .onMouseDown modifier to attach an action to this view. Inside the closure, you can put the code to handle the mouse-down event. In this case, we're just printing a message to the console when a mouse down is detected.

You can replace the print statement with your custom code to perform any desired action when a mouse-down event occurs.

This code should work for SwiftUI macOS applications, allowing you to respond to mouse-down events on a view.

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.