OSX (マウンテン ライオン) 用のアプリを開発するために、今日から Objective-C を使い始めました。テキストフィールドなど、他のオブジェクトにドラッグしたいボタンがたくさんあります。Apple の開発サイトのチュートリアルに従いましたが、ドラッグ部分が機能しませんでした (ドロップ部分が機能します。たとえば、ファイルをファインダーからテキスト ファイルにドラッグしてそのパスを表示できます)。
NSButton サブクラスを作成することから始めました。
@interface mp3OCDDraggableButton : NSButton
https://developer.apple.com/library/mac/#samplecode/CocoaDragAndDrop/Introduction/Intro.htmlで説明されているようにメソッドを実装しました 。
しかし物は動かない!
私はいくつかのログメッセージをmouseDown:に入れました。これは見ることができますが、それをmouseDragged:に置き換えてもそうではありません-これは何かを教えてくれますか?
誰でもこの機能を使用して簡単な例を投稿できますか? 機能するものが見つかりませんでした:\
よろしくお願いします!
これは、ドラッグ可能なボタンのこれまでのコードです。チュートリアルとほとんど同じです。
//myDraggableButton.h
@interface myDraggableButton : NSButton <NSDraggingSource, NSPasteboardItemDataProvider>
@end
と
//myDraggableButton.m
#import "myDraggableButton.h"
@implementation myDraggableButton
- (void)mouseDown:(NSEvent *)theEvent:(NSEvent*)event
{
NSLog(@"mouseDown");
NSPasteboardItem *pbItem = [NSPasteboardItem new];
[pbItem setDataProvider:self forTypes:[NSArray arrayWithObjects:NSPasteboardTypeString, nil]];
NSDraggingItem *dragItem = [[NSDraggingItem alloc] initWithPasteboardWriter:pbItem];
NSRect draggingRect = self.bounds;
[dragItem setDraggingFrame:draggingRect contents:[self image]];
NSDraggingSession *draggingSession = [self beginDraggingSessionWithItems:[NSArray arrayWithObject:dragItem] event:event source:self];
draggingSession.animatesToStartingPositionsOnCancelOrFail = YES;
draggingSession.draggingFormation = NSDraggingFormationNone;
}
- (NSDragOperation)draggingSession:(NSDraggingSession *)session sourceOperationMaskForDraggingContext:(NSDraggingContext)context
{
switch (context) {
case NSDraggingContextOutsideApplication:
return NSDragOperationCopy;
case NSDraggingContextWithinApplication:
default:
return NSDragOperationCopy;
break;
}
}
- (BOOL)acceptsFirstMouse:(NSEvent *)event
{
return YES;
}
- (void)pasteboard:(NSPasteboard *)sender item:(NSPasteboardItem *)item provideDataForType:(NSString *)type
{
if ( [type compare: NSPasteboardTypeTIFF] == NSOrderedSame ) {
[sender setData:[[self image] TIFFRepresentation] forType:NSPasteboardTypeTIFF];
} else if ( [type compare: NSPasteboardTypePDF] == NSOrderedSame ) {
[sender setData:[self dataWithPDFInsideRect:[self bounds]] forType:NSPasteboardTypePDF];
}
}
@end