Last active
August 9, 2023 03:05
-
-
Save colejd/8f07e41b0e3324a5e89523740d39a023 to your computer and use it in GitHub Desktop.
NSView that closes itself when clicking outside
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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
Sample usage:
(Presume some instance of
ModalView
calledmodal
exists already)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):