Con Swift 4, NSAttributedStringKeytiene una propiedad estática llamada foregroundColor. foregroundColortiene la siguiente declaración:
static let foregroundColor: NSAttributedStringKey
El valor de este atributo es un UIColorobjeto. Use este atributo para especificar el color del texto durante la representación. Si no especifica este atributo, el texto se representa en negro.
El siguiente código de Playground muestra cómo configurar el color del texto de una NSAttributedStringinstancia con foregroundColor:
import UIKit
let string = "Some text"
let attributes = [NSAttributedStringKey.foregroundColor : UIColor.red]
let attributedString = NSAttributedString(string: string, attributes: attributes)
El código siguiente muestra una posible UIViewControlleraplicación que se basa en NSAttributedStringel objeto de actualizar el color del texto y el texto de una UILabelde una UISlider:
import UIKit
enum Status: Int {
case veryBad = 0, bad, okay, good, veryGood
var display: (text: String, color: UIColor) {
switch self {
case .veryBad: return ("Very bad", .red)
case .bad: return ("Bad", .orange)
case .okay: return ("Okay", .yellow)
case .good: return ("Good", .green)
case .veryGood: return ("Very good", .blue)
}
}
static let minimumValue = Status.veryBad.rawValue
static let maximumValue = Status.veryGood.rawValue
}
final class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var slider: UISlider!
var currentStatus: Status = Status.veryBad {
didSet {
// currentStatus is our model. Observe its changes to update our display
updateDisplay()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Prepare slider
slider.minimumValue = Float(Status.minimumValue)
slider.maximumValue = Float(Status.maximumValue)
// Set display
updateDisplay()
}
func updateDisplay() {
let attributes = [NSAttributedStringKey.foregroundColor : currentStatus.display.color]
let attributedString = NSAttributedString(string: currentStatus.display.text, attributes: attributes)
label.attributedText = attributedString
slider.value = Float(currentStatus.rawValue)
}
@IBAction func updateCurrentStatus(_ sender: UISlider) {
let value = Int(sender.value.rounded())
guard let status = Status(rawValue: value) else { fatalError("Could not get Status object from value") }
currentStatus = status
}
}
Sin embargo, tenga en cuenta que realmente no necesita usarlo NSAttributedStringpara tal ejemplo y simplemente puede confiar en UILabel's texty textColorpropiedades. Por lo tanto, puede reemplazar su updateDisplay()implementación con el siguiente código:
func updateDisplay() {
label.text = currentStatus.display.text
label.textColor = currentStatus.display.color
slider.value = Float(currentStatus.rawValue)
}