Search code examples
iphoneiosios6autolayout

Stop a UIImageView from returning to its original location in a View?


I was working through a very simple Ray Wenderlich iOS "dragging" example, where 2 UIImageViews (a monkey and a banana) can be dragged around the screen. It utilizes a UIPanGestureRecognizer in the ViewController implementation file:

- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer {

    CGPoint translation = [recognizer translationInView:self.view];
    recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
                                         recognizer.view.center.y + translation.y);
    [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];

}

That works fine, and the monkey and banana stay at whatever position you drag them to. However, I wanted to have whichever UIImageView is clicked (touched) to become to top most view. I fooled around a little and came up with this line of code:

 [self.view bringSubviewToFront:recognizer.view];

I put that in the handlePan method, and it does bring whatever image clicked on (touched) to the front, but it resets the previous image to its original location on the screen. It doesn't do that if I omit the line of code which brings the touched subview to the front.

What is it about bringing the selected subview to the front that resets the other image to its original location? How would this be prevented in a UIPanGestureRecognizer? Without going the touchesBegan, touchesEnded, etc method route?

Obviously I'm new to ios programming, but I couldn't find an answer to what is probably a simple problem. Thanks guys...any help is appreciated...


Solution

  • I recreated your source here. The problem is the autolayout, you will need to disable it. Because when you bring the view to front, it will apply the rules to the other view to check the position, repositioning it in the original place.

    So, why it not happens while you are changing the frames ? When you are only changing frames it does not apply the autolayout rules every time you change the center of one view, it will only apply when your view container hierarchy change or when the view container frame change.

    Like you told you are doing a Ray Wenderlich tutorial, I will recomend you to check the tutorial about autolayout. The material in the Ray Wenderlich site is a good starting point.

    --

    Just a little help to disable the auto layout, at .xib and story boards, select the view and disable the checkbox:

    disabling the autolayout