Usar varios colores de fuente en una sola etiqueta
¿Hay alguna forma de usar dos, o incluso tres colores de fuente en una sola etiqueta en iOS?
Si el texto "hello, how are you" fuera usado como ejemplo, el "hello," sería azul, y el "how are you" sería verde?
¿Es esto posible, parece más fácil que crear varias etiquetas?
13 answers
En primer lugar inicializar de usted NSString y NSMutableAttributedString como a continuación.
var myString:NSString = "I AM KIRIT MODI"
var myMutableString = NSMutableAttributedString()
{[3] {} En[4]}ViewDidLoad
override func viewDidLoad() {
myMutableString = NSMutableAttributedString(string: myString, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:4))
// set label Attribute
labName.attributedText = myMutableString
super.viewDidLoad()
}
* * Su SALIDA: * *
MÚLTIPLES COLORES
Agregue el código de línea a continuación en su viewDidLoad para obtener varios colores en una cadena.
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSRange(location:10,length:5))
Salida de múltiples colores
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-27 06:05:06
Para @ Hems Moradiya
let attrs1 = [NSFontAttributeName : UIFont.boldSystemFontOfSize(18), NSForegroundColorAttributeName : UIColor.greenColor()]
let attrs2 = [NSFontAttributeName : UIFont.boldSystemFontOfSize(18), NSForegroundColorAttributeName : UIColor.whiteColor()]
let attributedString1 = NSMutableAttributedString(string:"Drive", attributes:attrs1)
let attributedString2 = NSMutableAttributedString(string:"safe", attributes:attrs2)
attributedString1.appendAttributedString(attributedString2)
self.lblText.attributedText = attributedString1
Swift 4
let attrs1 = [NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18), NSAttributedStringKey.foregroundColor : UIColor.green]
let attrs2 = [NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18), NSAttributedStringKey.foregroundColor : UIColor.white]
let attributedString1 = NSMutableAttributedString(string:"Drive", attributes:attrs1)
let attributedString2 = NSMutableAttributedString(string:"safe", attributes:attrs2)
attributedString1.append(attributedString2)
self.lblText.attributedText = attributedString1
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-07 13:37:38
Respuesta Actualizada para Swift 4
Puede usar fácilmente html dentro de la propiedad attributedText de la etiqueta UILabel para hacer fácilmente varios formatos de texto.
let htmlString = "<font color=\"red\">This is </font> <font color=\"blue\"> some text!</font>"
let encodedData = htmlString.data(using: String.Encoding.utf8)!
let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
do {
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
label.attributedText = attributedString
} catch _ {
print("Cannot create attributed String")
}
Respuesta Actualizada para Swift 2
let htmlString = "<font color=\"red\">This is </font> <font color=\"blue\"> some text!</font>"
let encodedData = htmlString.dataUsingEncoding(NSUTF8StringEncoding)!
let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
do {
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
label.attributedText = attributedString
} catch _ {
print("Cannot create attributed String")
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-08 08:31:14
Swift 4
Mediante el uso de la siguiente función de extensión, puede establecer directamente un atributo de color a una cadena atribuida y aplicar el mismo en su etiqueta.
extension NSMutableAttributedString {
func setColorForText(textForAttribute: String, withColor color: UIColor) {
let range: NSRange = self.mutableString.range(of: textForAttribute, options: .caseInsensitive)
// Swift 4.2 and above
self.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
// Swift 4.1 and below
self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
}
}
Pruebe la extensión anterior, usando una etiqueta:
let label = UILabel()
label.frame = CGRect(x: 60, y: 100, width: 260, height: 50)
let stringValue = "stackoverflow"
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
attributedString.setColorForText(textForAttribute: "stack", withColor: UIColor.black)
attributedString.setColorForText(textForAttribute: "over", withColor: UIColor.orange)
attributedString.setColorForText(textForAttribute: "flow", withColor: UIColor.red)
label.font = UIFont.boldSystemFont(ofSize: 40)
label.attributedText = attributedString
self.view.addSubview(label)
Resultado:
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-05 09:29:23
Usó la respuesta de rakeshbs para crear una extensión en Swift 2:
// StringExtension.swift
import UIKit
import Foundation
extension String {
var attributedStringFromHtml: NSAttributedString? {
do {
return try NSAttributedString(data: self.dataUsingEncoding(NSUTF8StringEncoding)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
} catch _ {
print("Cannot create attributed String")
}
return nil
}
}
Uso:
let htmlString = "<font color=\"red\">This is </font> <font color=\"blue\"> some text!</font>"
label.attributedText = htmlString.attributedStringFromHtml
O incluso para una línea
label.attributedText = "<font color=\"red\">This is </font> <font color=\"blue\"> some text!</font>".attributedStringFromHtml
Lo bueno de la extensión es que tendrás el atributo .attributedStringFromHtml
para todos los String
a lo largo de toda tu aplicación.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:47:36
Hacer uso de NSMutableAttributedString
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:4))
Ver más detalles aquí swift-using-attributed-strings
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-01 05:28:50
Swift 3.0
let myMutableString = NSMutableAttributedString(
string: "your desired text",
attributes: [:])
myMutableString.addAttribute(
NSForegroundColorAttributeName,
value: UIColor.blue,
range: NSRange(
location:6,
length:7))
Para obtener más colores, puede seguir agregando atributos a la cadena mutable. Más ejemplos aquí.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-21 10:35:51
Me gustó de esta manera
let yourAttributes = [NSForegroundColorAttributeName: UIColor.black, NSFontAttributeName: UIFont.systemFontOfSize(15)]
let yourOtherAttributes = [NSForegroundColorAttributeName: UIColor.red, NSFontAttributeName: UIFont.systemFontOfSize(25)]
let partOne = NSMutableAttributedString(string: "This is an example ", attributes: yourAttributes)
let partTwo = NSMutableAttributedString(string: "for the combination of Attributed String!", attributes: yourOtherAttributes)
let combination = NSMutableAttributedString()
combination.appendAttributedString(partOne)
combination.appendAttributedString(partTwo)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-31 17:10:01
SWIFT 3
En mi código , creo una extensión
import UIKit
import Foundation
extension UILabel {
func setDifferentColor(string: String, location: Int, length: Int){
let attText = NSMutableAttributedString(string: string)
attText.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueApp, range: NSRange(location:5,length:4))
attributedText = attText
}
}
Y esto para su uso
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.setDifferentColor(string: titleLabel.text!, location: 5, length: 4)
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-13 01:45:04
Ejemplo de Swift 3 usando la versión HTML.
let encodedData = htmlString.data(using: String.Encoding.utf8)!
let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
do {
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
label.attributedText = attributedString
} catch _ {
print("Cannot create attributed String")
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-03 17:54:28
Aquí está el código que admite La última versión de Swift a partir de marzo de 2017.
Swift 3.0
Aquí he creado una clase auxiliar y un método para el
public class Helper {
static func GetAttributedText(inputText:String, location:Int,length:Int) -> NSMutableAttributedString {
let attributedText = NSMutableAttributedString(string: inputText, attributes: [NSFontAttributeName:UIFont(name: "Merriweather", size: 15.0)!])
attributedText.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 0.401107, green: 0.352791, blue: 0.503067, alpha: 1.0) , range: NSRange(location:location,length:length))
return attributedText
}
}
En los Parámetros del Método, inputText: String-el texto que se mostrará en la etiqueta ubicación: Int-donde el estilo debe ser la aplicación, "0" como inicio de la cadena o algún valor válido como posición del carácter de la cadena longitud: Int - Desde la ubicación hasta cuántos caracteres es este estilo aplicable.
Consumir en otro método:
self.dateLabel?.attributedText = Helper.GetAttributedText(inputText: "Date : " + (self.myModel?.eventDate)!, location:0, length: 6)
Salida:
Nota: El color de la interfaz de usuario se puede definir color como UIColor.red
o colores definidos por el usuario como UIColor(red: 0.401107, green: 0.352791, blue: 0.503067, alpha: 1.0)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-20 17:15:43
func MultiStringColor(first:String,second:String) -> NSAttributedString
{
let MyString1 = [NSFontAttributeName : FontSet.MonsRegular(size: 14), NSForegroundColorAttributeName : FoodConstant.PUREBLACK]
let MyString2 = [NSFontAttributeName : FontSet.MonsRegular(size: 14), NSForegroundColorAttributeName : FoodConstant.GREENCOLOR]
let attributedString1 = NSMutableAttributedString(string:first, attributes:MyString1)
let attributedString2 = NSMutableAttributedString(string:second, attributes:MyString2)
MyString1.append(MyString2)
return MyString1
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-12 10:57:16
Para usar este NSForegroundColorAttributeName en la versión inferior de swift puede obtener problemas de identificador sin resolver cambie lo anterior a NSAttributedStringKey.ForegroundColor .
swift lower version swift latest version
Es decir, NSForegroundColorAttributeName == NSAttributedStringKey.foregroundColor
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-25 10:25:45