使用Swift处理触控板事件

时间:2015-12-27 18:17:17

标签: ios swift cocoa

来自apple here的开发者文档,我遇到了这个。

  

您可以选择跟踪和处理构成手势的“原始”触摸,而不是处理手势。

文档中的示例是针对Objective-C而不是针对Swift的。如何在全球范围内跟踪和处理Swift中的这些“原始”触摸?不只是在NSView中?

我的课程:

import Cocoa
import Security
import AppKit

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!
    @IBOutlet weak var dropMenu: NSMenu!
    @IBOutlet weak var resetView: NSView!
    @IBOutlet weak var resetWindow: NSPanel!
    @IBOutlet weak var keyLabel: NSTextField!

    let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1);

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        NSApp.setActivationPolicy(NSApplicationActivationPolicy.Accessory)
        let menuIcon = NSImage(named: "menuIcon")
        menuIcon?.template = true;
        statusItem.image = menuIcon;
        statusItem.menu = dropMenu;
    }

    @IBAction func quit(sender: NSMenuItem) {
        NSApplication.sharedApplication().terminate(self)
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        for touch: AnyObject! in touches {
            let touchLocation = touch.locationInNode(self)
            //Use touchLocation for example: button.containsPoint(touchLocation) meaning the user has pressed the button.
        }
    }

}

1 个答案:

答案 0 :(得分:3)

再次更新,NSEvent:

(touchesBegan UIEvent等适用于iOS,MacOS不同并使用NSEvent)

NSEvent是您想要查看的内容,您可以在其中使用mouseDown,mouseUp,mouseMove等,然后获取光标点:

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSResponder_Class/index.html#//apple_ref/occ/instm/NSResponder/mouseDown

mouseDown的Swift示例:

override func mouseDown(event: NSEvent) {
    let point: NSPoint = event.locationInView
    print("X: \'point.x'")
    print("Y: \'point.y'")
}

Objc示例:

- (void)mouseDown:(NSEvent *)event {
    NSLog( @"mouse down event: %@", event );
    NSPoint point = [event locationInWindow];
    NSLog( @"mouseDown location: (%d,%d)", point.x, point.y );
}

希望这有帮助。