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()
        }
    }
}

Logo

这里是“一人公司”的成长家园。我们提供从产品曝光、技术变现到法律财税的全栈内容,并连接云服务、办公空间等稀缺资源,助你专注创造,无忧运营。

更多推荐