简体   繁体   中英

Mouse over in a NSView subview

i have a subclass of NSView that handles Mouse events, inside that NSView i have a subview (which is another subclass of NSView). How can i handle Mouse Events for both NSViews.

What i want to achieve is the following:

A NSView where i got a character, when i move my mouse around inside that view the character rotate to follow the mouse. inside the same there are some Items, when the mouse hover over an item i want to display some information... how can achieve this?

basically: two classes receive and respond to mouse over.

Best Regards Kristian

i guess, you should play with CreateMouse Region and handle Mouse event like mouseenter , mouse exit on it,

refer following method of NSView

addTrackingRect : provide Rect where you would like to capture mouse event for that region you would get following event,

mouseDown

mouseUp

mouseEntered

mouseExited

and so on

Here is how we did in Swift 5:

class TrackingAreaView: NSView {

   private var isMouseOverTheView = false {
      didSet {
         backgroundColor = isMouseOverTheView ? .red : .green
      }
   }
   private lazy var area = makeTrackingArea()
   private var backgroundColor: NSColor? {
      didSet {
         setNeedsDisplay(bounds)
      }
   }

   init() {
      super.init(frame: NSRect()) // Zero frame. Assuming that we are in autolayout environment.
      isMouseOverTheView = false
   }

   required init?(coder: NSCoder) {
      fatalError()
   }

   public override func updateTrackingAreas() {
      removeTrackingArea(area)
      area = makeTrackingArea()
      addTrackingArea(area)
   }

   public override func mouseEntered(with event: NSEvent) {
      isMouseOverTheView = true
   }

   public override func mouseExited(with event: NSEvent) {
      isMouseOverTheView = false
   }

   private func makeTrackingArea() -> NSTrackingArea {
      return NSTrackingArea(rect: bounds, options: [.mouseEnteredAndExited, .activeInKeyWindow], owner: self, userInfo: nil)
   }

   open override func draw(_ dirtyRect: NSRect) {
      if let backgroundColor = backgroundColor {
         backgroundColor.setFill()
         dirtyRect.fill()
      } else {
         super.draw(dirtyRect)
      }
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM