java改变字符串的颜色_使用NSAttributedString更改字符串颜色?

2023-05-16

使用Swift 4, NSAttributedStringKey 有一个名为 foregroundColor 的静态属性 . foregroundColor 有以下声明:

static let foregroundColor: NSAttributedStringKey

此属性的值是UIColor对象 . 使用此属性指定渲染过程中文本的颜色 . 如果未指定此属性,则文本将以黑色呈现 .

以下Playground代码显示如何使用 foregroundColor 设置 NSAttributedString 实例的文本颜色:

import UIKit

let string = "Some text"

let attributes = [NSAttributedStringKey.foregroundColor : UIColor.red]

let attributedString = NSAttributedString(string: string, attributes: attributes)

下面的代码显示了一个可能的 UIViewController 实现,该实现依赖于 NSAttributedString ,以便从 UISlider 更新 UILabel 的文本和文本颜色:

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)

}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

java改变字符串的颜色_使用NSAttributedString更改字符串颜色? 的相关文章

随机推荐