Swift 4 ile NSAttributedStringKeystatik özelliği vardır foregroundColor. foregroundColoraşağıdaki beyana sahiptir:
static let foregroundColor: NSAttributedStringKey
Bu niteliğin değeri bir UIColornesnedir. Oluşturma sırasında metnin rengini belirtmek için bu niteliği kullanın. Bu niteliği belirtmezseniz, metin siyah olarak oluşturulur.
Aşağıdaki Playground kodu, aşağıdakilerle bir NSAttributedStringörneğin metin renginin nasıl ayarlanacağını gösterir foregroundColor:
import UIKit
let string = "Some text"
let attributes = [NSAttributedStringKey.foregroundColor : UIColor.red]
let attributedString = NSAttributedString(string: string, attributes: attributes)
Gösterileri Aşağıdaki kod olası UIViewControllerdayanır uygulama NSAttributedStringbir metin ve metin rengini güncellemek için UILabelbir den 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 {
updateDisplay()
}
}
override func viewDidLoad() {
super.viewDidLoad()
slider.minimumValue = Float(Status.minimumValue)
slider.maximumValue = Float(Status.maximumValue)
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
}
}
Bununla birlikte, NSAttributedStringböyle bir örnek için gerçekten kullanmanıza gerek olmadığını ve sadece UILabel's textve textColorözelliklerine güvenebileceğinizi unutmayın . Bu nedenle, updateDisplay()uygulamanızı aşağıdaki kodla değiştirebilirsiniz:
func updateDisplay() {
label.text = currentStatus.display.text
label.textColor = currentStatus.display.color
slider.value = Float(currentStatus.rawValue)
}