Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center text in a UILabel

How do you center the text inside a UILabel?

like image 665
Chris Avatar asked Sep 18 '10 23:09

Chris


People also ask

How do I center text in a label in HTML?

One way to center text or put it in the middle of the page is to enclose it within <center></center> tags. Inserting this text within HTML code would yield the following result: Center this text!

How do I center text in a label in Swift?

You can also change the label text alignment by change the UILabel object's textAlignment property value t0 NSTextAlignment. left , NSTextAlignment. center or NSTextAlignment. right .

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!


1 Answers

The Code is

[yourLabel setTextAlignment:UITextAlignmentCenter]; 

or (of course) the Obj-C 2.0 Dot-Syntax

yourLabel.textAlignment = UITextAlignmentCenter; 

For iOS 6 (and higher) you should use NSTextAlignmentCenter instead of UITextAlignmentCenter:

yourLabel.textAlignment = NSTextAlignmentCenter; 

Source

And if you want backward compatibiliy to iOS 5 also you can do this,

#ifdef __IPHONE_6_0 # define ALIGN_CENTER NSTextAlignmentCenter #else # define ALIGN_CENTER UITextAlignmentCenter #endif 

Swift 3

yourLabel.textAlignment = .center 
like image 139
Henrik P. Hessel Avatar answered Sep 24 '22 21:09

Henrik P. Hessel