我今天开始使用objective-c来为OSX(山狮)开发一个应用程序。我有一堆按钮,我想将它们拖到其他对象中,例如文本字段。我按照苹果开发网站上的教程进行操作,但我无法让拖动部分工作(例如,放置部分工作,我可以将文件从查找器拖动到文本文件中并显示其路径)。
我首先创建了一个 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