Skip to content

Instantly share code, notes, and snippets.

@colejd
Last active August 9, 2023 03:05
Show Gist options
  • Save colejd/8f07e41b0e3324a5e89523740d39a023 to your computer and use it in GitHub Desktop.
Save colejd/8f07e41b0e3324a5e89523740d39a023 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
}
}
}
@colejd
Copy link
Author

colejd commented Oct 5, 2017

Sample usage:

(Presume some instance of ModalView called modal exists already)

modal.addCloseOnOutsideClick()

Now modal will hide itself if the user clicks outside of it.

If you don't want the modal to close when clicking certain views (for example, a button that opens the view):

modal.addCloseOnOutsideClick(ignoring: [someView, someOtherView])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment