Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering a label in a UIView

What's the best way to center a label in a UIView? If you do something such as

UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(view.frame.origin.x / 2, view.frame.origin.y / 2, 50.0, 50.0)];

Then you're setting the origin point of the label to the center of the view. The best bet would be to set the center of the view to that point using the center property. So I tried using the following code:

UIView *aView = [[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
aView.backgroundColor = [UIColor darkGrayColor];
CGRect frame = aView.frame;

UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 125.0f, 30.0f)];
[aLabel setCenter:CGPointMake(frame.origin.x / 2, frame.origin.y / 2)];

That yields a label which is pretty much outside the bounds of the view in the upper left hand corner.

like image 529
Coocoo4Cocoa Avatar asked Apr 09 '09 23:04

Coocoo4Cocoa


People also ask

How do you center a label in view?

Use NSTextAlignmentCenter if what you have is the label already set and you want to center its content. This is the best answer, having the label frame is centered is not enough for centering the text, very useful if your labels are localized!

How do I change my UILabel text?

To change the font or the size of a UILabel in a Storyboard or . XIB file, open it in the interface builder. Select the label and then open up the Attribute Inspector (CMD + Option + 5). Select the button on the font box and then you can change your text size or font.


1 Answers

The main thing you are doing wrong is taking half the origin values, rather than half the sizes

However, you don't need to even calculate that in this case - just do something like the following:


UIView *aView = [[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
aView.backgroundColor = [UIColor darkGrayColor];

UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 125, 30)];
aLabel.center = aView.center;

(note, you don't need to force those coordinates to floats - in this case writing them as ints seems more readable).

Also, it's a matter of style - but since you're already using property syntax (aView.backgroundColor) you may as well use it for the center property too :-)

like image 92
philsquared Avatar answered Oct 05 '22 20:10

philsquared