我正在尝试实现一个简单的机制:拖动文件后,将其名称传递给标签。但我无法理解如何做到这一点。这是我的代码:H文件:
#import <Cocoa/Cocoa.h>
@interface DropView : NSView <NSDraggingDestination> {}
@property (assign) IBOutlet NSTextField *labelUrl; // <- label for file name
@property NSString *urlStr;
@end
M 文件:
#import "DropView.h"
@implementation DropView
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self registerForDraggedTypes:[NSArray arrayWithObject:NSURLPboardType]];
}
return self;
}
- (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
if ([sender draggingSourceOperationMask] & NSDragOperationCopy) {
return NSDragOperationLink;
}
return NSDragOperationNone;
}
- (BOOL)prepareForDragOperation:(id<NSDraggingInfo>)sender {
return YES;
}
- (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
NSPasteboard *pboard = [sender draggingPasteboard];
if ( [[pboard types] containsObject:NSURLPboardType] )
{
NSURL *fileURL = [NSURL URLFromPasteboard:pboard];
_urlStr = [[fileURL absoluteString] lastPathComponent]; // <- example "img.jpg"
[self.labelUrl setStringValue:_urlStr]; // <- this is not work
}
return YES;
}
-(void)awakeFromNib {
[_labelUrl setStringValue:@"no file name"];
}
@end
ps 老实说,我在这里和谷歌中搜索了答案,但没有找到。