我正在尝试一个简单的拖放应用程序:
- 我正在运行时创建一个 CameraIconView(NSView 的子类,包含一些图像视图、文本字段和一个弹出按钮)。
- 此视图包含在 CameraIconEnclosureBox(NSBox 的子类)中
- 要求是:用户应该能够将 CameraIconView 拖动到 CameraIconEnclosureBox 中的其他位置。
为了实现我的要求,我正在这样做:
- 在 CameraIconView 类中实现了以下方法-
-(void)mouseDown:(NSEvent *)e{
NSPoint location;
NSSize size;
NSPasteboard *pb = [NSPasteboard pasteboardWithName:@"CameraIconContainer"];
location.x = ([self bounds].size.width - size.width)/2;
location.y = ([self bounds].size.height - size.height)/2;
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self];
[pb declareTypes:[NSArray arrayWithObject:IconDragDataType] owner:self];
[pb setData:data forType:IconDragDataType];
[self dragImage:[NSImage imageNamed:@"camera_icon.png"] at:location offset:NSZeroSize event:e pasteboard:pb source:self slideBack:NO];
}
2.在CameraIconEnclosureBox类中实现以下方法-
- (void)awakeFromNib{
[self registerForDraggedTypes:[NSArray arrayWithObject:IconDragDataType]];
}
- (NSDragOperation)draggingEntered:(id < NSDraggingInfo >)sender{
return NSDragOperationEvery;
}
- (BOOL)performDragOperation:(id < NSDraggingInfo >)sender{
return YES;
}
- (void)concludeDragOperation:(id < NSDraggingInfo >)sender{
NSPoint dropLocation = [sender draggingLocation];
float x = dropLocation.x;
float y = dropLocation.y;
NSLog(@"dragOperationConcluded! draggingLocation: (%f, %f)",x,y);
NSPasteboard *pb = [sender draggingPasteboard];
NSLog(@"Pasteboard name- %@",[pb name]);
NSData *draggedData = [pb dataForType:IconDragDataType];
CameraIconView *object = [NSKeyedUnarchiver unarchiveObjectWithData:draggedData];
NSLog(@"object - %@ / cameraNo : %@/ operatorName : %@",object,[[object cameraNo] stringValue],[[object operatorName] stringValue]);
// the cameraNo and operatorName are properties defined within CameraIconView class
// the above log is returning (null) for both properties
float width = [object frame].size.width;
float height = [object frame].size.height;
NSLog(@"width - %f / height - %f",width,height);
[object setFrame:NSMakeRect(x, y, width, height)];
}
实现这些方法后,我能够执行拖放操作,但无法执行拖放操作,尽管调用了 CameraIconEnclosureBox 中的所有拖动委托方法。
谁能建议我可能错在哪里或其他更好的方法来实现我的要求?
谢谢,
米拉杰