Skip to content

Instantly share code, notes, and snippets.

@ulian-onua
Forked from colejd/ModalView.swift
Created February 12, 2021 19:51
Show Gist options
  • Save ulian-onua/a5304ddd8c87a708500b9f9964e37125 to your computer and use it in GitHub Desktop.
Save ulian-onua/a5304ddd8c87a708500b9f9964e37125 to your computer and use it in GitHub Desktop.
NSView that closes itself when clicking outside
// MIT License - © 2017 Jonathan Cole.
import Cocoa
/**
A view with the ability to hide itself if the user clicks outside of it.
*/
class ModalView: NSView {
private var monitor: Any?
deinit {
// Clean up click recognizer
removeCloseOnOutsideClick()
}
/**
Creates a monitor for outside clicks. If clicking outside of this view or
any views in `ignoringViews`, the view will be hidden.
*/
func addCloseOnOutsideClick(ignoring ignoringViews: [NSView]? = nil) {
monitor = NSEvent.addLocalMonitorForEvents(matching: NSEventMask.leftMouseDown) { (event) -> NSEvent? in
if !self.frame.contains(event.locationInWindow) && self.isHidden == false {
// If the click is in any of the specified views to ignore, don't hide
for ignoreView in ignoringViews ?? [NSView]() {
let frameInWindow: NSRect = ignoreView.convert(ignoreView.bounds, to: nil)
if frameInWindow.contains(event.locationInWindow) {
// Abort if clicking in an ignored view
return event
}
}
// Getting here means the click should hide the view
// Perform your hiding code here
self.isHidden = true
}
return event
}
}
func removeCloseOnOutsideClick() {
if monitor != nil {
NSEvent.removeMonitor(monitor!)
monitor = nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment