Set text to fit UILabel and center in SWIFT

I am trying to set the text according to the size of the UILabel , and also to center. I do this programmatically. It looks like this:

enter image description here

As you can see, the text leaves the screen and is not centered.

This is my code:

 let questions = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ac faucibus tellus." questionsLabel = UILabel(frame: CGRectMake(10, 10, questionsView.frame.size.width - 20, 80)) questionsLabel.text = questions questionsLabel.font = UIFont(name: Font.FuturaMedium, size: 25) questionsLabel.sizeToFit() questionsLabel.numberOfLines = 0 questionsLabel.textAlignment = NSTextAlignment.Center questionsView.addSubview(questionsLabel) 

What am I doing wrong?

+7
uilabel swift uiview
source share
1 answer
 questionsLabel.sizeToFit() 

Makes the frame fit the size of the text. What are you looking for:

 questionsLabel.adjustsFontSizeToFitWidth = true 

This changes the font size according to the width of the label. (However, note that this will reduce the font only.)

 questionsLabel.textAlignment = NSTextAlignment.Center 

Centers the text inside the label.frame. Therefore, if you do it higher. And make sure the mark is centered and correct. You do not need to do anything to center the text.

Swift 3:

 questionsLabel.textAlignment = .center 
+25
source share

All Articles