开发者

Mouse over in a NSView subview

开发者 https://www.devze.com 2023-02-03 04:28 出处:网络
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.

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


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)
      }
   }
}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消