问题
I'd like to handle when user drag and drop text ( not file which contain text ) to my app's dock icon. How should i do that?
回答1:
The easiest way to accept text dropped on the Dock icon is to implement a service that accepts text.
In your Info.plist:
<dict>
<key>NSMenuItem</key>
<dict>
<key>default</key>
<string>Search in HoudahSpot</string>
</dict>
<key>NSMessage</key>
<string>search</string>
<key>NSPortName</key>
<string>HoudahSpot</string>
<key>NSRequiredContext</key>
<dict>
<key>NSServiceCategory</key>
<string>public.text</string>
</dict>
<key>NSSendTypes</key>
<array>
<string>NSStringPboardType</string>
</array>
<key>Service description</key>
<string>Starts a HoudahSpot search for the selected text</string>
</dict>
In your application delegate:
- (void)search:(NSPasteboard *)pboard userData:(NSString *)data error:(NSString **)error
{
NSArray *types = [pboard types];
if ([types containsObject:NSStringPboardType]) {
NSString *searchString = [pboard stringForType:NSStringPboardType];
NSLog(@"%@", searchString);
}
}
You can also catch the event by registering for it in -applicationWillFinishLaunching:
NSAppleEventManager *appleEventManager = [NSAppleEventManager sharedAppleEventManager];
[appleEventManager setEventHandler:self
andSelector:@selector(handleOpenContentsEvent:withReplyEvent:)
forEventClass:kCoreEventClass
andEventID:kAEOpenContents];
And handling it:
- (void)handleOpenContentsEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent
{
NSString *string = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
NSLog(@"%@", string);
}
You still need to declare a service in your Info.plist for the drop to be accepted.
回答2:
Swift recipe:
In Info.plist
<key>NSServices</key>
<array>
<dict>
<key>NSSendTypes</key>
<array>
<string>NSStringPboardType</string>
</array>
<key>NSMessage</key>
<string>droppedText</string>
<key>NSMenuItem</key>
<dict>
<key>default</key>
<string>Text Drop</string>
</dict>
</dict>
</array>
In AppDelegate
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
print(kUTTypeUTF8PlainText)
NSApplication.sharedApplication().servicesProvider = self
}
//When text is dragged over the icon
func droppedText(pboard: NSPasteboard, userData:String, error: NSErrorPointer)
{
if let pboardString = pboard.stringForType(NSStringPboardType){
print(pboardString)
}
}
来源:https://stackoverflow.com/questions/27420016/osx-drag-and-drop-text-not-file-to-app-dock-icon