Question

I'm struggling with dragging and dropping an UILabel from one UIView to another UIView. Please check the code below:

  CGPoint point = [[[event allTouches] anyObject] locationInView:self.view];
  UIControl *control = sender;
  control.center = point;

Using this code I am not able to drag properly.

Was it helpful?

Solution

A subview can't jump out of its subiewView and move into other View by itself.

What you have to do is in touchesBegan remove the label from its parentView. add anotherLabel exactly at the same position but in view which is superview of both the views (to be dragged from and to be dropped in).

Now in touchesMoved. move it based on touch position.

And in touchesEnd. find the position and loop over your views and find which view user dragged it to and add a new label as a subview in it on that position.

Update basic code (fix any syntax error if there are )

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
   //get position
   // get label on that position
   [label removeFromSuperView];
   newLabel = [[UILabel alloc] init]; //make newLabel iVar
   newLabel.textColor = label.textColor ; // etc copy values
   [self.view addSubView:newLabel]; //positioned at label
}

touchesMoved {
   //getPosition
   newLabel.position = position;
}

touchesEnded {
   //getPosition.
   self.view.subviews; // loop and find which view has the position.

   UILabel *finalLabel = [[UILabel alloc] init];
   finalLabel.center = newLabel.center;

   [newLabel removeFromSuperView];

   [ViewToBeDropped addSubview:finalLabel];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top