为什么更改 UILabel 的文本不会重置 iOS 13 上的文本属性?

Ben*_*iby 5 ios swift

在 iOS 12 上,如果更改 UILabel 的文本,则会重置文本属性。然而,在 iOS 13 上,当文本更改时,颜色、字体、字母间距等文本属性将被保留。发生了什么变化?

一个例子:

label.text = "Hello world"
let attributedString = NSMutableAttributedString(string: label.text ?? " ")
attributedString.addAttributes([.foregroundColor: UIColor.red], range: NSRange(location: 0, length: attributedString.length))
label.attributedText = attributedString        
label.text = "What's up world" // Text is red on iOS 13, default black on iOS 12.
Run Code Online (Sandbox Code Playgroud)

Moj*_*ini 4

好像从 iOS 13 开始,如果你设置并归因于整个文本,它将持续存在!如果您不在文本的整个范围内应用该属性,则其行为与以前一样。

您有一些选择来解决它:

  1. 没有将其应用于整个范围(大多数情况下都会发生):
attributedString.addAttributes([
    .foregroundColor: UIColor.red,
    .backgroundColor: UIColor.green
], range: NSRange(location: 0, length: 3))
Run Code Online (Sandbox Code Playgroud)
  1. 执行版本检查(也许需要一点扩展)
@available(iOS 13.0, *)
extension UILabel {
    func setTextWithoutAttributes(_ text: String) {
        // Get rid of the holding attributes instance as Asperi mentioned or in another way you like
        self.attributedText = nil
        // Set the text
        self.text = text
    }
}
Run Code Online (Sandbox Code Playgroud)