Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement