Search code examples
iosobjective-cautolayoutcenteringcgrectmake

iOS Programmatically Center Objects


I am updating an app for iPhone 6 Plus support. On one of the views that is set up programmatically, running on 5S or below has all views centered the way they should be. However, on the 6 Plus, it is scooted over slightly to the left. How can I adjust this code to keep it centered horizontally in all versions?

[self.logInView.usernameField setFrame:CGRectMake(35.0f, 125.0f, 250.0f, 50.0f)];
[self.logInView.passwordField setFrame:CGRectMake(35.0f, 175.0f, 250.0f, 50.0f)];
[self.fieldsBackground setFrame:CGRectMake(35.0f, 125.0f, 250.0f, 100.0f)];
[self.logInView.logInButton setFrame:CGRectMake(35.0f, 235.0f, 250.0f, 40.0f)];

Solution

  • [self.logInView.usernameField setFrame:CGRectMake(self.view.center.x - 125, 0, 250.0f, 50.0f);];
    [self.logInView.passwordField setFrame:CGRectMake(self.view.center.x - 125, 175.0f, 250.0f, 50.0f)];
    [self.fieldsBackground setFrame:CGRectMake(self.view.center.x - 125, 125.0f, 250.0f, 100.0f)];
    [self.logInView.logInButton setFrame:CGRectMake(self.view.center.x - 125, 235.0f, 250.0f, 40.0f)];
    

    you can use this code to get laid down UI horizontal well on all iOS devices.