Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

macos - Changing NSCursor for NSView above an NSTextView

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 other NSViews on top of it.

Similar to the question linked above, I setup a tracking area, and applied the cursor as such:

class CursorChangingView: NSView {
    override func updateTrackingAreas() {
        let trackingArea = NSTrackingArea(rect: 
    }

    override func cursorUpdate(event: NSEvent) {
        NSCursor.arrowCursor().set()
    }
}

It does seem to work when hovering, but immediately goes back to the IBeam Cursor, which is the default cursor for NSTextViews under this CursorChangingView.

Is this the proper way of applying changing the cursor when hovering over a certain NSView, and is the NSTextView under it overriding my overrriding?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...