【发布时间】:2012-11-25 19:35:57
【问题描述】:
我今天开始使用objective-c ,以便为OSX(山狮)开发一个应用程序。 我有一堆按钮,我想将它们拖到其他对象中,例如文本字段。我按照苹果开发网站上的教程进行操作,但我无法让拖动部分正常工作(例如,拖放部分工作,我可以将文件从 finder 拖动到文本文件中并显示其路径)。
我首先创建了一个 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
【问题讨论】:
-
请发布您的代码。在不知道自己写了什么的情况下,几乎不可能知道从哪里开始。
-
您还没有实现
mouseDown:方法。您实现的事件处理程序方法是mouseDown::,采用两个参数,即您标记为theEvent和event的变量。没有任何东西会向您发送这样的消息,因此永远不会调用该方法;相反,您将收到一条mouseDown:消息(带有一个参数),但您没有实现任何响应它的方法。删除“theEvent:(NSEvent *)”部分(留下“mouseDown:(NSEvent *)event”)以解决该问题。
标签: objective-c cocoa drag-and-drop nsbutton