make a window that follows your mouse wherever you go in swift

To create a macOS window that follows the mouse wherever you go, you need to use mouse tracking and handle mouse events. Here's how you can do it in Swift:

First, create a new macOS project and add a window to the Main.storyboard. Set its title and size as desired.

Next, add an NSView to the window and set its width and height to be equal to the window's content view. This will be the view that we'll use to track the mouse.

In the ViewController.swift file, add the following code:

main.swift
import Cocoa

class ViewController: NSViewController {

    @IBOutlet weak var trackingView: NSView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        trackingView.wantsLayer = true
        trackingView.layer?.backgroundColor = NSColor.red.cgColor
        
        // Track mouse movement
        NSEvent.addGlobalMonitorForEvents(matching: [.mouseMoved]) { [weak self] (mouseEvent) in
            self?.moveWindow(with: mouseEvent)
        }
    }
    
    func moveWindow(with mouseEvent: NSEvent) {
        // Move window to the mouse position
        let mouseLocation = NSEvent.mouseLocation
        if let window = view.window, window.isMovableByWindowBackground {
            let frame = window.frame
            window.setFrameOrigin(NSPoint(x: mouseLocation.x - frame.width / 2, y: mouseLocation.y - frame.height / 2))
        }
    }

}
873 chars
29 lines

This code sets the background color of the trackingView to red for visual reference, and adds a global event monitor for mouse movement. When the mouse moves, the moveWindow method is called, which moves the window to the current mouse position.

Note that we're checking whether the window is movable by its background or not, to avoid issues with windows that are not meant to be moved.

Finally, connect the trackingView IBOutlet to the NSView you added to the storyboard, and run the app. You should be able to see the red view and move the window by moving the mouse around.

gistlibby LogSnag