在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
实现,该实现依赖于从a NSAttributedString
来更新a的文本和文本颜色:UILabel
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
此类示例,而只需依赖UILabel
的text
和textColor
属性即可。因此,可以用updateDisplay()
以下代码替换实现:
func updateDisplay() {
label.text = currentStatus.display.text
label.textColor = currentStatus.display.color
slider.value = Float(currentStatus.rawValue)
}