OSX将文本(不是文件)拖放到app dock图标

时间:2014-12-11 10:02:02

标签: macos cocoa text

当用户将文本(不包含文本的文件)拖放到我的应用程序的停靠栏图标时,

希望处理。我该怎么做?

2 个答案:

答案 0 :(得分:1)

接受停靠在Dock图标上的文本的最简单方法是实现接受文本的服务。

在您的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>

在您的申请代表中:

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

你也可以通过在-applicationWillFinishLaunching中注册它来捕获事件:

NSAppleEventManager     *appleEventManager  = [NSAppleEventManager sharedAppleEventManager];

    [appleEventManager setEventHandler:self
                           andSelector:@selector(handleOpenContentsEvent:withReplyEvent:)
                         forEventClass:kCoreEventClass
                            andEventID:kAEOpenContents];

处理它:

- (void)handleOpenContentsEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent
{
    NSString *string = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];

    NSLog(@"%@", string);
}

您仍需要在Info.plist中声明服务,以便接受删除。

答案 1 :(得分:0)

斯威夫特食谱:

在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>

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