【macOS(swift)笔记-1】鼠标悬停按钮时改变鼠标光标图案

张开发
2026/5/11 16:18:20 15 分钟阅读

分享文章

【macOS(swift)笔记-1】鼠标悬停按钮时改变鼠标光标图案
import Cocoa class HxButton: NSButton { var trackingArea: NSTrackingArea? var isCursorInside false override func awakeFromNib() { super.awakeFromNib() setupTrackingArea() } override func viewDidMoveToWindow() { super.viewDidMoveToWindow() setupTrackingArea() } // 为按钮添加鼠标跟踪区域 func setupTrackingArea() { // 移除旧的 tracking area如果存在 if let oldTrackingArea trackingArea { self.removeTrackingArea(oldTrackingArea) } // 创建新的 tracking area let newTrackingArea NSTrackingArea( rect: self.bounds, options: [.mouseEnteredAndExited, .activeInActiveApp, .inVisibleRect],//[.mouseEnteredAndExited, .activeInKeyWindow], 无效 [.mouseEnteredAndExited, .activeAlways],无效 [.mouseEnteredAndExited, .activeInActiveApp],无效 owner: self, userInfo: nil ) // 添加 tracking area 到按钮 self.addTrackingArea(newTrackingArea) trackingArea newTrackingArea } override func mouseEntered(with event: NSEvent) { print(Mouse entered) // 在这里添加你想要的逻辑 // // 鼠标进入时设置为手型指针 // NSCursor.pointingHand.push() NSCursor.pointingHand.set() isCursorInside true } override func mouseExited(with event: NSEvent) { print(Mouse exited) // 在这里添加你想要的逻辑 // // 鼠标离开时恢复默认指针 // NSCursor.pop() NSCursor.arrow.set() isCursorInside false } // 这个方法不能省否则界面一刷新鼠标光标就会立刻被重置成默认的 override func cursorUpdate(with event: NSEvent) { if isCursorInside { NSCursor.pointingHand.set() } else { NSCursor.arrow.set() } } }

更多文章