Nic Hubbard
Nic Hubbard

Reputation: 42139

iOS: UILabel centered in view

I have a UISplitViewController and am trying to center (horizontal and vertically) a UILabel in the right view controller. When it loads in portrait the label looks correct, but if you rotate it to landscape the label is no longer centered vertically. I am using:

CGSize size = self.view.frame.size;
UILabel *noResults = [[UILabel alloc] initWithFrame:CGRectMake(0, 40.0f, size.width, size.height)];
noResults.text = @"No people were found.";
noResults.textColor = [UIColor blackColor];
noResults.textAlignment = UITextAlignmentCenter;
noResults.backgroundColor = [UIColor clearColor];
noResults.textColor = [UIColor darkGrayColor];
noResults.font = [UIFont systemFontOfSize:16.0];
noResults.shadowColor = [UIColor whiteColor];
noResults.shadowOffset = CGSizeMake(0, 1);
noResults.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.noResultsLabel = noResults;
[self.view addSubview:noResultsLabel];
[noResults release];

I thought it would automatically resize itself when I used a autoresize mask?

Upvotes: 0

Views: 1621

Answers (1)

sergio
sergio

Reputation: 69027

You should also specify that the margins are flexible, like this:

 noResults.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin |  UIViewAutoresizingFlexibleRightMargin;

By using this code, you will get the button repositioned horizontally. If you also want it to be repositioned vertically, also specify UIViewAutoresizingFlexibleTopMargin and UIViewAutoresizingFlexibleBottomMargin.

Upvotes: 1

Related Questions