2010-10-17 19 views
6

Come posso avere uno UILabel con due colori diversi per il carattere? Avrò testo in due stringhe diverse e voglio fare il testo con la prima stringa come rosso e il secondo come verde. La lunghezza di entrambe le stringhe è variabile.UILabel con due colori diversi testo

+0

Ho dovuto farlo anche in un progetto. Ho usato questa classe da un altro post, ma è solo per una ** singola linea **, non so se è abbastanza per te. [iPhone - UILabel contenente testo con più font contemporaneamente] (http://stackoverflow.com/questions/1417346/iphone-uilabel-contain-text-with-multiple-fonts-at-the-same-time) –

risposta

7

Non è possibile farlo entro un UILabel s. Ma il mio suggerimento è che invece di utilizzare più UILabel concentrarsi solo su NSAttributedString. Trova UIControllers che disegna NSAttributedString perché UILabel, UITextView non supporta NSAttributedString.

PS: se si prevede di distribuire un'applicazione iOS6 o poi, come UILabel ora supportano NSAttributedString, si dovrebbe usare UILabel direttamente invece di OHAttributedLabel come è ora supportato nativamente dal sistema operativo.

+0

Questa risposta non è più corretta perché ad es. UILabel supporta NSAttributedString da iOS 6. – brainray

+0

@brainray Ho aggiornato la risposta alla fine dell'anno stesso. Per favore controllalo. – KingofBliss

4

UILabel può avere solo un colore. O hai bisogno di un elemento più sofisticato, o - probabilmente più facile - basta usare due etichette separate. Utilizzare [yourLabel sizeToFit]; e posizionarli di conseguenza.

+0

okkk proverò ad esplorare la proprietà sizeToFit di uilabel, grazie per aver risposto – pankaj

8

Prova TTTAttributedLabel. È una sottoclasse di UILabel che supporta NSAttributedString s, il che renderebbe facile avere più colori, font e stili nella stessa stringa.


Edit: In alternativa, se non si desidera che il 3 ° dipendenze partito e stanno prendendo di mira iOS 6, UILabel ha ora la proprietà attributedText.

+1

Bello. NSAttributedString è sicuramente la strada da percorrere - e la classe che stai suggerendo sembra molto carina. – iceydee

0

In iOS 6 UILabel ha la proprietà NSAttributoString. Quindi usalo.

1

Swift 4
(Nota: la notazione per la chiave stringa attribuito è cambiato in rapida 4)

Qui è un'estensione per NSMutableAttributedString, che aggiungono/set di colori su stringa/testo.

extension NSMutableAttributedString { 

    func setColor(color: UIColor, forText stringValue: String) { 
     let range: NSRange = self.mutableString.range(of: stringValue, options: .caseInsensitive) 
     self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range) 
    } 

} 

Ora, provate al di sopra di estensione con UILabel e vediamo risultato

let label = UILabel() 
label.frame = CGRect(x: 40, y: 100, width: 280, height: 200) 
let red = "red" 
let blue = "blue" 
let green = "green" 
let stringValue = "\(red)\n\(blue)\n&\n\(green)" 
label.textColor = UIColor.lightGray 
label.numberOfLines = 0 
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue) 
attributedString.setColor(color: UIColor.red, forText: red) // or use direct value for text "red" 
attributedString.setColor(color: UIColor.blue, forText: blue) // or use direct value for text "blue" 
attributedString.setColor(color: UIColor.green, forText: green) // or use direct value for text "green" 
label.font = UIFont.systemFont(ofSize: 26) 
label.attributedText = attributedString 
self.view.addSubview(label) 


Ecco soluzione in Swift 3:

extension NSMutableAttributedString { 
     func setColorForText(textToFind: String, withColor color: UIColor) { 
     let range: NSRange = self.mutableString.range(of: textToFind, options: .caseInsensitive) 
      if range != nil { 
      self.addAttribute(NSForegroundColorAttributeName, value: color, range: range) 
      } 
     } 

} 


func multicolorTextLabel() { 
     var string: NSMutableAttributedString = NSMutableAttributedString(string: "red\nblue\n&\ngreen") 
     string.setColorForText(textToFind: "red", withColor: UIColor.red) 
     string.setColorForText(textToFind: "blue", withColor: UIColor.blue) 
     string.setColorForText(textToFind: "green", withColor: UIColor.green) 
     labelObject.attributedText = string 
    } 

Risultato:

enter image description here

+0

Ho appena provato questo in iOS 11 e ho ottenuto un errore nell'estensione .. self.addAttributes ([NSForegroundColorAttributeName: color], range: range) – August

+0

@August - Si prega di condividere il messaggio di errore. Fammi anche conoscere la versione rapida del tuo progetto. Potresti provare con l'estensione Swift 3 e il tuo progetto ha Swift 4. Condividi le informazioni relative agli errori, quindi posso aiutarti. – Krunal

+0

Sì, è un progetto Swift 4 e ha utilizzato l'estensione Swift 4 che hai condiviso. Si trattava di un errore di sintassi, non di un errore di compilazione/runtime. Doc »https://developer.apple.com/documentation/foundation/nsmutableattributedstring/1414304-addattributes – August

Problemi correlati