2015-03-25 16 views
7

Sto provando a impostare il testo per adattarlo alle dimensioni di un UILabel e anche a essere centrato. Lo sto facendo a livello di codice. Questo è ciò che sembra attualmente:Impostazione del testo per adattarsi alle dimensioni di una UILabel e al centro in SWIFT

enter image description here

Come si può vedere, il testo sta andando fuori dallo schermo e non è anche centrato.

Questo è il mio codice:

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) 

Che cosa sto facendo di sbagliato?

risposta

25
questionsLabel.sizeToFit() 

Fa corrispondere la cornice alla dimensione del testo. Quello che state cercando è:

questionsLabel.adjustsFontSizeToFitWidth = true 

Questo cambia la dimensione del carattere in base alla larghezza dell'etichetta. (Tuttavia, faccio notare che sarà ridimensionare solo il tipo di carattere.)

questionsLabel.textAlignment = NSTextAlignment.Center 

Centri il testo all'interno del label.frame. Quindi se fai quanto sopra. E assicurati che l'etichetta sia centrata e che la larghezza sia corretta. Non dovresti fare altro per centrare il testo.

Swift 3:

questionsLabel.textAlignment = .center 
Problemi correlati