我正在尝试一个简单的拖放应用程序:
-
我正在运行时创建一个CameraIconView(NSView的子类,包含一些图像视图、文本字段和一个弹出按钮)。
-
此视图包含在CameraIconEnclosingBox(NSBox的子类)中
-
要求是:用户应该能够在CameraIconEnclosingBox中的其他位置拖动CameraIconView。
为了实现我的要求,我正在执行以下操作:
-
在CameraIconView类中实现了以下方法-
-(无效)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。在CameraIconEnclosingBox类中实现了以下方法-
- (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)];
}
在实现这些方法之后,我可以执行拖放操作,但拖放操作不起作用,尽管CameraIconEnclosingBox中的所有拖动委托方法都被调用。
有人能告诉我哪里可能是错的或者其他更好的方法来实现我的需求吗?
谢谢,
米拉杰