Con Swift 4, NSAttributedStringKeyha una proprietà statica chiamata foregroundColor. foregroundColorha la seguente dichiarazione:
static let foregroundColor: NSAttributedStringKey
Il valore di questo attributo è un UIColoroggetto. Utilizzare questo attributo per specificare il colore del testo durante il rendering. Se non si specifica questo attributo, il testo viene visualizzato in nero.
Il seguente codice Playground mostra come impostare il colore del testo di NSAttributedStringun'istanza con foregroundColor:
import UIKit
let string = "Some text"
let attributes = [NSAttributedStringKey.foregroundColor : UIColor.red]
let attributedString = NSAttributedString(string: string, attributes: attributes)
Il codice seguente mostra una possibile UIViewControllerimplementazione che si basa su NSAttributedStringper aggiornare il testo e il colore del testo di a UILabelda a 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
}
}
Si noti, tuttavia, che non si ha realmente bisogno di utilizzare NSAttributedStringper un tale esempio e può semplicemente fare affidamento su UILabel's texte textColorproprietà. Pertanto, è possibile sostituire l' updateDisplay()implementazione con il seguente codice:
func updateDisplay() {
label.text = currentStatus.display.text
label.textColor = currentStatus.display.color
slider.value = Float(currentStatus.rawValue)
}