我今天开始使用objective-c来开发OSX(山狮)的应用程序 . 我有一堆按钮,我想将它们拖动到其他对象中,例如文本字段 . 我按照苹果's dev site, but I wans'上的教程来使拖动部件工作(拖放部分工作,例如,我可以将文件从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
2 回答
我为死灵法术道歉,但我在试图自己实现这个问题时偶然发现了这个问题,并希望分享答案,因为它可能对其他人有用 .
此解决方案使用
NSActionCell
和NSControl
上的类别,因为我需要能够拖动多个控件类型,而不仅仅是按钮 . 您可以根据自己的需求/课程进行调整 .在隐藏/取消隐藏控件时,我已经注释了与不希望的淡入淡出动画的变通方法有关的代码 . 我摆弄着隐含的动画等,但无法想出更好的方法 . 黑客确实运行良好,但我离开了窗口实现代码 .
可能问题是你用
NSPasteboardTypeString
调用-setDataProvider:forTypes:
但是你的-pasteboard:item:provideDataForType:
在传递那种类型时什么都不做?