Mac_Play Mac_Play - 4 months ago 62
iOS Question

Drag and drop uilabel from one view to another view -iOS

Am struggling with dragging and droping an uilabl from one view to another view.Please check the below code and help me.

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


Using the below code am not able to drag properly.

Answer

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];
}