Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to add mouseOver events to a tableView in cocoa?

I want to make my tableView act like this:
When the mouse swipe over a certain row, the row will be highlighted, just like the mouseOver event of a button

like image 825
Edward Avatar asked Dec 08 '22 08:12

Edward


1 Answers

It took me some time to work on it based on this hint.

It works for me, correct me if I'm wrong.

Tested with Swift 3.0.2 on macOS 10.12.2 and Xcode 8.2.1

//
// Created by longkai on 30/12/2016.
// Copyright (c) 2016 xiaolongtongxue.com. All rights reserved.
//

import Cocoa

class InboxTableCellView: NSTableCellView {
    // MARK: - Outlets
    @IBOutlet weak var title: NSTextField!
    @IBOutlet weak var sender: NSTextField!
    @IBOutlet weak var time: NSTextField!
    @IBOutlet weak var snippet: NSTextField!

    // MARK: - Mouse hover
    deinit {
        removeTrackingArea(trackingArea)
    }

    private var trackingArea: NSTrackingArea!

    override func awakeFromNib() {
        super.awakeFromNib()
        self.trackingArea = NSTrackingArea(
            rect: bounds,
            options: [NSTrackingAreaOptions.activeAlways, NSTrackingAreaOptions.mouseEnteredAndExited,/* NSTrackingAreaOptions.mouseMoved */],
            owner: self,
            userInfo: nil
        )
        addTrackingArea(trackingArea)
    }

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

        NSColor(red: 0.96, green: 0.96, blue: 0.96, alpha: 1.00).set()

        // mouse hover
        if highlight {
            let path = NSBezierPath(rect: bounds)
            path.fill()
        }

        // draw divider
        let rect = NSRect(x: 0, y: bounds.height - 2, width: bounds.width, height: bounds.height)
        let path = NSBezierPath(rect: rect)
        path.fill()
    }

    private var highlight = false {
        didSet {
            setNeedsDisplay(bounds)
        }
    }

    override func mouseEntered(with event: NSEvent) {
        super.mouseEntered(with: event)
        if !highlight {
            highlight = true
        }
    }

    override func mouseExited(with event: NSEvent) {
        super.mouseExited(with: event)
        if highlight {
            highlight = false
        }
    }
}
like image 96
longkai Avatar answered Apr 24 '23 14:04

longkai