mea36
mea36

Reputation: 746

iphone - How to center dynamic sized text

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?

Upvotes: 0

Views: 2983

Answers (3)

devsri
devsri

Reputation: 6183

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

Upvotes: 2

hotpaw2
hotpaw2

Reputation: 70673

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.

Upvotes: 1

Vjy
Vjy

Reputation: 2135

Modify setAutoresizingMask property to your needs

Upvotes: 0

Related Questions