要使透明的NSView子类处理鼠标事件,您需要遵循以下步骤:
class CustomView: NSView {
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
setupView()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupView()
}
private func setupView() {
wantsLayer = true
layer?.backgroundColor = NSColor.clear.cgColor
}
}
hitTest(_:)
方法。override func hitTest(_ point: NSPoint) -> NSView? {
let hitView = super.hitTest(point)
return hitView == self ? nil : hitView
}
override func updateTrackingAreas() {
super.updateTrackingAreas()
if let trackingArea = trackingArea {
removeTrackingArea(trackingArea)
}
let options: NSTrackingArea.Options = [.mouseEnteredAndExited, .activeInKeyWindow]
let trackingArea = NSTrackingArea(rect: bounds, options: options, owner: self, userInfo: nil)
addTrackingArea(trackingArea)
}
override func mouseEntered(with event: NSEvent) {
Swift.print("Mouse entered")
}
override func mouseExited(with event: NSEvent) {
Swift.print("Mouse exited")
}
现在,您的透明NSView子类将处理鼠标事件,并在鼠标进入和退出视图时触发mouseEntered
和mouseExited
方法。
领取专属 10元无门槛券
手把手带您无忧上云