Skip to content

Instantly share code, notes, and snippets.

@importRyan
importRyan / whenHovered.md
Last active July 1, 2024 22:26
Reliable SwiftUI mouse hover

Reliable mouseEnter/Exit for SwiftUI

Kapture 2021-03-01 at 14 43 39

On Mac, SwiftUI's .onHover closure is not always called on mouse exit, particularly with high cursor velocity. A grid of targets or with finer target shapes will often have multiple targets falsely active after the mouse has moved on.

It is easy to run back to AppKit's safety. Below is a SwiftUI-like modifier for reliable mouse-tracking. You can easily adapt it for other mouse tracking needs.

import SwiftUI
import Foundation
// MARK: - Protocol
public protocol Notifier {
associatedtype Notification: RawRepresentable
}
public extension Notifier where Notification.RawValue == String {
@ericdke
ericdke / makePNGFromView.swift
Created June 7, 2015 19:47
Swift: create PNG from NSView
func makePNGFromView(view: NSView) {
var rep = view.bitmapImageRepForCachingDisplayInRect(view.bounds)!
view.cacheDisplayInRect(view.bounds, toBitmapImageRep: rep)
if let data = rep.representationUsingType(NSBitmapImageFileType.NSPNGFileType, properties: [:]) {
data.writeToFile("/xxx/image.png", atomically: false)
}
}
@jgwhite
jgwhite / with-history.js
Created May 31, 2011 10:56
Simple pushState wrapper
// WithHistory v1.0.0
// hello@withassociates.com
//
// Usage:
// $(document).bind('WithHistory.urlDidChange', function() { ... });
// window.withHistory = new WithHistory();
// window.withHistory.pushState(newUrl) // push new url
// window.withHistory.url(); // get current url
var WithHistory = function() {