Search code examples
iosobjective-ccentering

How to center a UIButton after device is rotated in iOS


I have created a UIButton programmatically and horizontally centered it using the following code

    button.center = CGPointMake(self.view.center.x, 50);

When device is rotated, it's no longer in the center. How can I fix this problem? Thanks in advance.


Solution

  • Kevin is correct, but a better solution would be to set the button's center in your view controller's willAnimateRotationToInterfaceOrientation:duration: method.

    - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration
    {
        button.center = CGPointMake(self.view.center.x, 50);
    }
    

    He uses the didRotateFromInterfaceOrientation:fromInterfaceOrientation method, which, as the Apple documentation states "this method might be used to reenable view interactions, start media playback again, or turn on expensive drawing or live updates."

    In the case of laying out subviews, the willAnimateRotationToInterfaceOrientation:duration: will provide a smoother transition, as it is called from within the rotation's animation block.