Changing NSCursor for NSView above an NSTextView

后端 未结 3 734
借酒劲吻你
借酒劲吻你 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:19

    All you need is to subclass a custom view, override awakeFromNib method, add the custom tracking area for [.mouseMoved, .activeAlways] events: NSTrackingArea Info there. There is no need to override resetCursorRects and/or updateTrackingAreas. All you need is to override mouseMoved method and set the desired cursor there:

    Note about discardCursorRects method:

    From the docs

    You need never invoke this method directly

    Xcode 9 • Swift 4

    import Cocoa
    
    class CursorChangingView: NSView {
    
        override func awakeFromNib() {
    
            addTrackingArea(NSTrackingArea(rect: bounds, options: [.activeAlways, .mouseMoved], owner: self, userInfo: nil))
    
            wantsLayer = true
            layer?.backgroundColor = NSColor.cyan.cgColor
            layer?.borderColor = NSColor.black.cgColor
            layer?.borderWidth = 1
        }
    
        @objc override func mouseMoved(with theEvent: NSEvent) {
            NSCursor.pointingHand.set()
        }
    }
    

    Sample

提交回复
热议问题