永远不会调用MouseMoved函数

时间:2016-02-22 22:19:06

标签: swift macos cocoa

我试图在NSViewController中覆盖mouseMoved函数。

import Cocoa

class MainViewController: NSViewController {

override var acceptsFirstResponder: Bool {get {return true} }

@IBOutlet var background: RandomNumberBackground!
override func viewDidLoad() {
    super.viewDidLoad() 
}

override func awakeFromNib() {
    NSTimer.scheduledTimerWithTimeInterval(0.04, target: background, selector: "updateNumbers", userInfo: nil, repeats: true)
}

@IBAction func btnLevelClicked(sender: AnyObject) {
      self.presentViewControllerAsSheet(LevelScrollController())
}

override func mouseMoved(theEvent: NSEvent) {
    Swift.print("MOVED!")
}

}

我已经覆盖了acceptFirstResponder但是从未调用过mouseMoved。为什么?哪里出错?

5 个答案:

答案 0 :(得分:1)

您需要在windows属性中设置acceptsMouseMovedEvents。

将以下代码添加到applicationDidFinishLaunching

func applicationDidFinishLaunching(aNotification: NSNotification) {
    window.acceptsMouseMovedEvents = true
}

答案 1 :(得分:1)

这是我需要在视图中跟踪鼠标移动时添加的代码。 它比以前的答案更长,但这是正确完成操作的必要条件:)

class MyView: NSView {
    
    var trackingArea: NSTrackingArea?

    // MARK: - Tracking area management

    /// Will install tracking area on the view if a window is set
    override func viewDidMoveToSuperview() {
        super.viewDidMoveToSuperview()
        installTrackingArea()
    }
    
    /// Install tracking area if window is set, remove previous one if needed.
    func installTrackingArea() {
        guard let window = window else { return }
        window.acceptsMouseMovedEvents = true
        if trackingArea != nil { removeTrackingArea(trackingArea!) }
        let trackingOptions = [.activeAlways, .mouseEnteredAndExited, .mouseMoved]
        trackingArea = NSTrackingArea(rect: bounds, 
                                      options: trackingOptions, 
                                      owner: self, userInfo: nil)
        self.addTrackingArea(trackingArea!)
    }
    
    /// Called when layout is modified
    override func updateTrackingAreas() {
        super.updateTrackingAreas()
        installTrackingArea()
    }

    //MARK: - Mouse Events handling

    override func mouseExited(with event: NSEvent) {
        print("Good bye mouse")
    }
    
    override func mouseEntered(with event: NSEvent) {
        let point = self.convert(event.locationInWindow, from: nil)
        print("Hello mouse, welcome at \(point)")
    }

    override func mouseMoved(with event: NSEvent) {
        let point = self.convert(event.locationInWindow, from: nil)
        print("Mouse moved \(point)")
    }
}

答案 2 :(得分:0)

答案 3 :(得分:0)

在swift 3中,您可以将它放在viewDidLoad()

self.view!.window?.acceptsMouseMovedEvents = true;

答案 4 :(得分:0)

无需在窗口上设置任何内容。

跟踪区域是处理此问题的正确方法。

只需将其添加到VC的vieWDidLoad()方法中即可。

let ta = NSTrackingArea(rect: CGRect.zero, options: [.activeAlways, .inVisibleRect, .mouseMoved], owner: self, userInfo: nil)
self.view.addTrackingArea(ta)