iphone - How to center dynamic sized text
I have text that I want to display centered (both vertically and horizontally) within 开发者_Python百科bounds of a box. The text is dynamic so I can't just set it in IB.
Anyone have any ideas?
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!!
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.
Modify setAutoresizingMask property to your needs
精彩评论