2015-12-27 120 views
1

從apple here的開發人員文檔中,我發現了這一點。使用Swift處理觸控板事件

您可以選擇跟蹤和處理組成手勢的「原始」觸摸,而不是處理手勢。

本文檔中的示例針對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. 
     } 
    } 

} 

回答

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

斯威夫特鼠標按下的例子:

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

希望這有助於。

+0

嘿,我無法導入UIEvent,任何線索?我查看了框架列表,並且UIKit不在那裏。 – user3813948

+0

你在Swift 1或2上? –

+0

im on swift 2.0 – user3813948