libdo

Untitled

Oct 6th, 2017
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // MIT License - © 2017 Jonathan Cole.
  2.  
  3. import Cocoa
  4.  
  5. /**
  6. A view with the ability to hide itself if the user clicks outside of it.
  7. */
  8. class ModalView: NSView {
  9. private var monitor: Any?
  10.  
  11. deinit {
  12. // Clean up click recognizer
  13. removeCloseOnOutsideClick()
  14. }
  15.  
  16. /**
  17. Creates a monitor for outside clicks. If clicking outside of this view or
  18. any views in `ignoringViews`, the view will be hidden.
  19. */
  20. func addCloseOnOutsideClick(ignoring ignoringViews: [NSView]? = nil) {
  21. monitor = NSEvent.addLocalMonitorForEvents(matching: NSEventMask.leftMouseDown) { (event) -> NSEvent? in
  22. if !self.frame.contains(event.locationInWindow) && self.isHidden == false {
  23.  
  24. // If the click is in any of the specified views to ignore, don't hide
  25. for ignoreView in ignoringViews ?? [NSView]() {
  26. let frameInWindow: NSRect = ignoreView.convert(ignoreView.bounds, to: nil)
  27. if frameInWindow.contains(event.locationInWindow) {
  28. // Abort if clicking in an ignored view
  29. return event
  30. }
  31. }
  32.  
  33. // Getting here means the click should hide the view
  34. // Perform your hiding code here
  35. self.isHidden = true
  36. }
  37. return event
  38. }
  39. }
  40.  
  41.  
  42. func removeCloseOnOutsideClick() {
  43. if monitor != nil {
  44. NSEvent.removeMonitor(monitor!)
  45. monitor = nil
  46. }
  47. }
  48.  
  49. }
Add Comment
Please, Sign In to add comment