Take the 2-minute tour ×

I have text that I want to display centered (both vertically and horizontally) within bounds of a box. The text is dynamic so I can't just set it in IB.

Anyone have any ideas?

share|improve this question
This can be your answer –  Hemang Feb 7 '13 at 10:31

3 Answers 3

up vote 2 down vote accepted

You can use the following method to get the expected size as

CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font];

Using this set the frame of your label as

yourLabel.frame = CGRectMake( yourX, yourY, expectedLabelSize.width , expectedLabelSize.height;

The same could be done with UIButton and UItextArea. You can also you use UITextField but the height would not be adjustible.

Also you can set the textalignment property to Centre as yourLabel.textAlignment = UITextAlignmentCenter

Hope it works!!

share|improve this answer
Hey, do communicate by accepting the answer if it helps .... thanks –  devsri Mar 2 '11 at 13:53
Thanks for the reply but I don't see how this vertically aligns my text. –  mea36 Mar 3 '11 at 17:06
yeah ..... you are ryt .... i am also not sure of the vertical alignment..... as far as i know there is no in built way to align the same.... :( –  devsri Mar 4 '11 at 5:58

You can use the height from the contentSize property of a UITextView to set the contentOffset property of a UITextView such that the text height is centered in the text view's frame height. Similar for width. A text view does not have to be editable if you just want to display text.

You could also use a UIWebView containing appropriate CSS to center content.

share|improve this answer

Modify setAutoresizingMask property to your needs

share|improve this answer

Your Answer


