В Swift 4 NSAttributedStringKeyимеет статическое свойство с именем foregroundColor. foregroundColorимеет следующую декларацию:
static let foregroundColor: NSAttributedStringKey
Значением этого атрибута является UIColorобъект. Используйте этот атрибут, чтобы указать цвет текста во время рендеринга. Если этот атрибут не указан, текст отображается черным цветом.
Следующий код Playground показывает, как установить цвет текста NSAttributedStringэкземпляра с помощью foregroundColor:
import UIKit
let string = "Some text"
let attributes = [NSAttributedStringKey.foregroundColor : UIColor.red]
let attributedString = NSAttributedString(string: string, attributes: attributes)
В приведенном ниже коде показана возможная UIViewControllerреализация, которая используется NSAttributedStringдля обновления текста и цвета текста a UILabelиз 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
}
}
Тем не менее, обратите внимание, что вам не нужно использовать NSAttributedStringдля такого примера, и вы можете просто полагаться на UILabels textи textColorсвойства. Поэтому вы можете заменить свою updateDisplay()реализацию следующим кодом:
func updateDisplay() {
label.text = currentStatus.display.text
label.textColor = currentStatus.display.color
slider.value = Float(currentStatus.rawValue)
}