【发布时间】:2026-01-18 22:30:01
【问题描述】:
我很难使用NSTrackingArea 更新光标以显示我的自定义可拖动NSView 可以调整大小的位置。这是一个例子:
句柄的NSRect:
var handleBottomLeft: NSRect {
NSRect(x: self.bounds.origin.x,
y: self.bounds.origin.y,
width: handleMargin + borderWidth,
height: handleMargin + borderWidth)
}
追踪区域:
var bottomLeftTrackingArea: NSTrackingArea?
override func updateTrackingAreas() {
if let area = bottomLeftTrackingArea {
self.removeTrackingArea(area)
}
bottomLeftTrackingArea = nil
bottomLeftTrackingArea = NSTrackingArea(rect: handleBottomLeft, options: [.activeInKeyWindow, .cursorUpdate], owner: self, userInfo: nil)
addTrackingArea(bottomLeftTrackingArea!)
super.updateTrackingAreas()
}
最后,光标更新:
override func cursorUpdate(with event: NSEvent) {
switch event.trackingArea {
case bottomLeftTrackingArea:
print("pointing hand")
NSCursor.pointingHand.set()
default:
print("arrow")
super.cursorUpdate(with: event)
}
}
光标在进入或离开蓝色框时应该会发生变化,但只有 50-75% 的时间会发生这种情况。这是一个光标进入时不改变但离开时改变的示例。
【问题讨论】:
标签: swift macos cocoa nstrackingarea