xcodeviewviewdidlayoutsubviews

Xcode - viewDidLayoutSubviews


i have a view inside a viewController, i wanted to start the smaller view outside the viewController in the left, and animate it to the centre when i press a button. so i made it like this:

override func viewDidLayoutSubviews() {

    smallView.center = CGPointMake(smallView.center.x - 400, smallView.center.y)

}

And it works perfectly!, the problem is i have a text view inside that smaller view, and every time i start editing it it jumps outside of the main viewController right where it was, and i have to press the button again to bring it inside. How to fix this?

PS: i tried positioning it to the centre when i start editing the text view like this:

func textViewDidBeginEditing(textView: UITextView) {

    smallView.center = CGPointMake(smallView.center.x + 400, smallView.center.y)

}

But it doesn't work. and the method is connected to the textView properly(delegate)

PS2: i also have imagePickerController inside my viewController.


Solution

  • OK, as you're using Auto Layout.

    The first rule of Auto Layout (you will see this in any Auto Layout book) is that you absolutely cannot touch the frame or center of a view directly.

    // don't do these
    myView.frame = CGRectMake(0, 0, 100, 100);
    
    // ever
    myView.center = CGPointMake(50, 50);
    

    You can get the frame and center but you can never set the frame or center.

    In order to move stuff around using Auto Layout you need to update the constraints.

    For instance if I set up a view called myView and want it to grow and shrink in height I would do something like...

    1. Set the top constraint to the superview at 0.
    2. Set the left constraint to the superview at 0.
    3. Set the right constraint to the superview at 0.
    4. Set the height constraint to 50 (for example) and save it in a property called heightConstraint.

    Now to animate the change in height I do this...

    self.heightConstraint.constant = 100;
    
    [UIView animateWithDuration:1.0
                     animations:^ {
                         [self.view layoutIfNeeded];
                     }];
    

    This will then animate the height from 50 (where it was when I set it) to 100.

    This is the same for ANY animation of views using Auto Layout. If (for instance) I had saved the left constraint I could change that and it would increase and decrease the gap from the left edge of the superview to myView.

    There are several really good tutorials about AutoLayout on the Ray Wenderlich site. I'd suggest you take a look at them.

    Whatever you do, I'd strongly suggest not just disabling Auto Layout. If you don't know how to use Auto Layout then you will very quickly fall behind with iOS 8 and the new device sizes.