在开发Mac App 时,经常需要变换鼠标样式。实现鼠标样式的变换需要用到两个类:
NSCursor
、NSTrackingArea
下面一个最常用的业务场景:鼠标移到一串文字上时,鼠标变成小手指
首先需要定义一个追踪区域:
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()
分别将鼠标设置为箭头和小手指。
可以很清楚的看出:当鼠标移入时,设为小手指;鼠标移出时,设为箭头。
参照:
https://stackoverflow.com/questions/32447739/changing-nscursor-for-nsview-above-an-nstextview
https://developer.apple.com/documentation/appkit/nscursor?language=objc
网友评论