0

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?

mea36
  • 746
  • 2
  • 9
  • 17

3 Answers3

2

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!!

devsri
  • 6,173
  • 5
  • 32
  • 40
  • Thanks for the reply but I don't see how this vertically aligns my text. – mea36 Mar 03 '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 04 '11 at 05:58
1

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.

hotpaw2
  • 70,107
  • 14
  • 90
  • 153
0

Modify setAutoresizingMask property to your needs

Vjy
  • 2,106
  • 3
  • 22
  • 34