Avec Swift 4, NSAttributedStringKeya une propriété statique appelée foregroundColor. foregroundColora la déclaration suivante:
static let foregroundColor: NSAttributedStringKey
La valeur de cet attribut est un UIColorobjet. Utilisez cet attribut pour spécifier la couleur du texte lors du rendu. Si vous ne spécifiez pas cet attribut, le texte est rendu en noir.
Le code Playground suivant montre comment définir la couleur du texte d'une NSAttributedStringinstance avec foregroundColor:
import UIKit
let string = "Some text"
let attributes = [NSAttributedStringKey.foregroundColor : UIColor.red]
let attributedString = NSAttributedString(string: string, attributes: attributes)
Le code ci-dessous montre une UIViewControllerimplémentation possible qui s'appuie sur NSAttributedStringpour mettre à jour le texte et la couleur du texte d'un à UILabelpartir d'un 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
}
}
Notez toutefois que vous n'avez pas vraiment besoin d'utiliser NSAttributedStringun tel exemple et peut simplement compter sur UILabell » textet textColorpropriétés. Par conséquent, vous pouvez remplacer votre updateDisplay()implémentation par le code suivant:
func updateDisplay() {
label.text = currentStatus.display.text
label.textColor = currentStatus.display.color
slider.value = Float(currentStatus.rawValue)
}