要响应鼠标的mouseEntered
、mouseExited
、mouseMoved
回调方法,需要为对应的NSView实例添加上NSTrackingArea(监视区域)~
如下代码,将NSTrackingArea(监视区域)添加到了self.view
上:
import Cocoa
class ViewController: NSViewController {
var kb_V: NSView?
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
self.view.wantsLayer = true
self.view.layer?.backgroundColor = NSColor.purple.cgColor
kb_V = NSView(frame: NSMakeRect(100, 100, 300, 300))
self.view .addSubview(kb_V!)
kb_V!.wantsLayer = true
kb_V!.layer?.backgroundColor = NSColor.cyan.cgColor
//添加——追踪‘鼠标’的区域
//【一】通过枚举项的原始值`rawValue`来通过“|”或运算,得到新的NSTrackingArea.Options来使用
let opt = (
NSTrackingArea.Options.mouseEnteredAndExited.rawValue |
NSTrackingArea.Options.mouseMoved.rawValue |
NSTrackingArea.Options.activeAlways.rawValue
)
let trackingArea = NSTrackingArea(rect: kb_V!.frame, options: NSTrackingArea.Options(rawValue: opt), owner:self, userInfo: nil)
self.view .addTrackingArea(trackingArea)
// //【二】通过枚举项合成一个数组,作为NSTrackingArea.Options来使用
// let trackingArea = NSTrackingArea(rect: kb_V!.frame, options: [NSTrackingArea.Options.mouseEnteredAndExited, NSTrackingArea.Options.mouseMoved, NSTrackingArea.Options.activeAlways], owner:self, userInfo: nil)
// self.view .addTrackingArea(trackingArea)
}
//MARK:Mouse鼠标的响应
override func mouseMoved(with event: NSEvent) {
//event.type——判断鼠标的操作、event.locationInWindow——获取鼠标的位置
let eventType = event.type
let locPoint = event.locationInWindow
print("eventType:\(eventType.rawValue),locPoint:\(locPoint)")//eventType.rawValue为5
}
override func mouseEntered(with event: NSEvent) {
//event.type——判断鼠标的操作、event.locationInWindow——获取鼠标的位置
let eventType = event.type
let locPoint = event.locationInWindow
print("eventType:\(eventType.rawValue),locPoint:\(locPoint)")//eventType.rawValue为8
kb_V?.layer?.backgroundColor = NSColor.brown.cgColor //颜色改为棕色
}
override func mouseExited(with event: NSEvent) {
//event.type——判断鼠标的操作、event.locationInWindow——获取鼠标的位置
let eventType = event.type
let locPoint = event.locationInWindow
print("eventType:\(eventType.rawValue),locPoint:\(locPoint)")//eventType.rawValue为9
kb_V?.layer?.backgroundColor = NSColor.cyan.cgColor //颜色改回青色
}
}
效果:a.当鼠标移入到NSTrackingArea(监视区域)的范围时,打印event.type
为8和(该时刻)鼠标的位置—颜色改为棕色、b.当鼠标在NSTrackingArea(监视区域)的范围内进行移动时,打印event.type
为5和鼠标的位置、c.当鼠标移出 NSTrackingArea(监视区域)的范围时,打印event.type
为9和(该时刻)鼠标的位置—颜色改回青色!
其他更多鼠标/键盘事件的监听,可参考《Mac 鼠标/键盘事件的监听和模拟》