Pregunta

¿Cómo puedo tener un UILabel con dos colores diferentes para la fuente? Voy a tener el texto en dos series diferentes y quiero hacer que el texto con la primera cadena como Red y el segundo como verde . La longitud de la cadena tanto es variable.

¿Fue útil?

Solución

No se puede hacer esto dentro de un UILabels. Pero mi sugerencia es que en lugar de utilizar múltiples UILabel sólo se concentra en NSAttributedString. Encuentra UIControllers que dibujar NSAttributedString porque UILabel, UITextView no son compatibles con NSAttributedString.

PS:. Si va a distribuir una aplicación más adelante iOS6 o, como UILabel ahora son compatibles con NSAttributedString, se debe utilizar UILabel directamente en lugar de OHAttributedLabel como ahora es compatible de forma nativa por el sistema operativo

Otros consejos

Trate TTTAttributedLabel . Es una subclase de UILabel que soporta NSAttributedStrings, lo que haría que sea fácil tener múltiples colores, fuentes y estilos en la misma cadena.


Editar:. Como alternativa, si no desea que la tercera parte y la dependencia está apuntando el IOS 6, UILabel ahora tiene la propiedad attributedText

UILabel sólo puede tener un de color. O se necesita un elemento más sofisticado, o - probablemente más fácil - sólo tiene que utilizar dos etiquetas separadas. Uso [yourLabel sizeToFit]; y el lugar en consecuencia.

Swift 4 gratis ( Nota: notación para una cadena con atributos clave se cambia en rápida 4 )

Aquí es una extensión para NSMutableAttributedString, ese color adicionado / juego de cuerdas / texto.

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)
    }

}

Ahora, trata por encima de la extensión con UILabel y ver resultado

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)


Aquí está la solución en 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
    }

Resultados:

introducir descripción de la imagen aquí

En iOS 6 UILabel tiene la propiedad NSAttributedString. Por lo tanto el uso que.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top