Drag and drop without removing UIButton
I'm implementing a drag and drop system in an iphone app. So far I managed to implement the draggable button and it is working fine. This is t开发者_开发知识库he code that I have:
First, I assign the action to the button:
[button addTarget:self action:@selector(imageMoved:withEvent:) forControlEvents:UIControlEventTouchDragInside];
then, I create the drag:
- (IBAction) imageMoved:(id) sender withEvent:(UIEvent *) event
{
NSLog(@"moved");
CGPoint point = [[[event allTouches] anyObject] locationInView:self.view];
UIControl *control = sender;
control.center = point;
}
However, what I want to achieve is that the button being dragged doesn't gets removed from where it is. So I thought of one solution that is to create a new button similar to the first and move the this newly created button. But I having trouble in implementing this last part. Any help? Thanks very much!
- (IBAction) imageMoved:(id) sender withEvent:(UIEvent *) event {
NSLog(@"moved");
CGPoint point = [[[event allTouches] anyObject] locationInView:self.view];
if (![self.view viewWithTag:11]) {
NSData *archivedData = [NSKeyedArchiver archivedDataWithRootObject:(UIButton*)sender];
UIButton *anotherButton =(UIButton*) [NSKeyedUnarchiver unarchiveObjectWithData:archivedData];
anotherButton.tag = 11;
UIImage *senderImage=[(UIButton *)sender imageForState:UIControlStateNormal];
CGImageRef cgImage = [senderImage CGImage];
UIImage *copyOfImage = [[UIImage alloc] initWithCGImage:cgImage];
[anotherButton setImage:copyOfImage forState:UIControlStateNormal];
[self.view addSubview:anotherButton];
}
[self.view viewWithTag:11].center = point;
}
To remove the restriction you can add two events on the origin button like so:
[button addTarget:self action:@selector(imageMoved:withEvent:) forControlEvents:UIControlEventTouchDragInside];
[button addTarget:self action:@selector(imageMoved:withEvent:) forControlEvents:UIControlEventTouchDragOutside];
This way the event will fire too when you exit the bounds of the current view (your button) and you'll be able to move the new button all arround the superview.
精彩评论