IOS: Transfer ownership of the UIView while something happens?

At the moment when I get touchesBegan , I want removeFromSuperview affected view and addSuperview have a new parent view, and then continue to get the strokes. However, I find that sometimes this does not work. In particular, touchesMoved and touchesEnded never called.

Is there a trick for working properly? This is for implementing drag and drop behavior when the view is initially scrollable.

Thanks.

+7
source share
2 answers

Instead

 [transferView removeFromSuperView]; [newParentView addSubview:transferView]; 

Use only:

 [newParentView addSubview:transferView]; 

The documentation states: "There can be only one view in the views. If the view already has a supervisor and this view is not the recipient, this method deletes the previous supervisor before making the receiver a new supervisor."

Therefore, there is no need to use removeFromSuperView, because it is processed by addSubview. I noticed that removeFromSuperView terminates any current touches without calling touchhesEnded. If you use addSubview only, the touch is not interrupted.

+7
source

You need to process your strokes in the supervisor, and not in the view that you want to disable. This will allow you to turn off viewing without losing touch. When you do this, you will have to check yourself if a touch occurs in a specific sub-item that you want to disable. You can do this in many ways, but here are a few ways to get you started:

Converting objects / points to another representation:

 [view convertRect:rect toView:subview]; [view convertPoint:point toView:subview]; 

Here are some ways to check if a point is in a view:

 [subView hitTest:point withEvent:nil]; CGRectContainsPoint(subview.frame, point); //No point conversion needed [subView pointInside:point withEvent:nil]; 

In general, it is better to use UIGestureRecognizers. For example, if you use UIPanGestureRecognizer, you must create a method that the gesture recognizer can recognize, and in this method you do your job. For example:

 - (void) viewPanned:(UIPanGestureRecognizer *)pan{ if (pan.state == UIGestureRecognizerStateBegan){ CGRect rect = subView.frame; newView = [[UIView alloc] initWithFrame:rect]; [subView removeFromSuperview]; [self addSubview:newView]; } else if (pan.state == UIGestureRecognizerStateChanged){ CGPoint point = [pan locationInView:self]; newView.center = point; } else { //Do cleanup or final view placement } } 

Then you start the recognizer, assign it to the target (usually self) and add it:

 [self addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(viewPanned:)]]; 

Now self (which will control the supervisor above it) will respond to pan movements.

0
source

All Articles