Mac鼠标样式设置

2021-03-09  本文已影响0人  本帅不良

在开发Mac App 时,经常需要变换鼠标样式。实现鼠标样式的变换需要用到两个类:NSCursorNSTrackingArea

下面一个最常用的业务场景:鼠标移到一串文字上时,鼠标变成小手指

首先需要定义一个追踪区域:

let area = NSTrackingArea.init(rect: bounds, options: [.activeAlways,.mouseEnteredAndExited], owner: self, userInfo: nil)
self.addTrackingArea(area)

接下来,需要实现追踪的方法:

    override func mouseExited(with event: NSEvent) {
        super.mouseExited(with: event)
        NSCursor.arrow.set()
    }
    
    override func mouseEntered(with event: NSEvent) {
        super.mouseEntered(with: event)
        NSCursor.pointingHand.set()
    }

其中NSCursor.arrow.set()NSCursor.pointingHand.set()分别将鼠标设置为箭头和小手指。
可以很清楚的看出:当鼠标移入时,设为小手指;鼠标移出时,设为箭头。

demo:https://gitee.com/pengzhiyao/tutoral.git

参照:
https://stackoverflow.com/questions/32447739/changing-nscursor-for-nsview-above-an-nstextview
https://developer.apple.com/documentation/appkit/nscursor?language=objc

上一篇下一篇

猜你喜欢

热点阅读