Changing NSCursor for NSView above an NSTextView

后端 未结 3 744
借酒劲吻你
借酒劲吻你 2020-12-10 07:33

Found a similar question to mine(this), but my issues seems to be a bit more associated with view hierarchy.

I have a NSTextView, then as sibling views, several othe

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 08:26

    Thanks @Leo Dabus for your answer, but I managed to solve it, so I will post my answer too.

    In my case, for some reason, mouseEntered and mouseEntered did not work at all.

    So here is my code that finally got it to work:

    class CursorChangingView: NSView {
        let trackingArea: NSTrackingArea?
        func setupTracking() {
            if self.trackingArea == nil {
                self.trackingArea = NSTrackingArea(rect: self.bounds, options: NSTrackingAreaOptions.ActiveAlways | NSTrackingAreaOptions.MouseMoved | NSTrackingAreaOptions.CursorUpdate | NSTrackingAreaOptions.MouseEnteredAndExited | NSTrackingAreaOptions.ActiveInActiveApp, owner: self, userInfo: nil)
                self.addTrackingArea(self.trackingArea!)
            }
        }
    
        override func updateTrackingAreas() {
            self.trackingArea = NSTrackingArea(rect: self.bounds, options: NSTrackingAreaOptions.ActiveAlways | NSTrackingAreaOptions.CursorUpdate | NSTrackingAreaOptions.MouseEnteredAndExited | NSTrackingAreaOptions.ActiveInActiveApp, owner: self, userInfo: nil)
            self.addTrackingArea(self.trackingArea!)
        }
    
        override func resetCursorRects() {
            self.discardCursorRects()
            self.addCursorRect(self.bounds, cursor: NSCursor.arrowCursor())
        }
    
        override func mouseMoved(theEvent: NSEvent) {
            NSCursor.arrowCursor().set()
        }
    }
    

    It might be a little excessive, but worked, so will share this as my own solution.

提交回复
热议问题