在 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)
好像从 iOS 13 开始,如果你设置并归因于整个文本,它将持续存在!如果您不在文本的整个范围内应用该属性,则其行为与以前一样。
您有一些选择来解决它:
attributedString.addAttributes([
.foregroundColor: UIColor.red,
.backgroundColor: UIColor.green
], range: NSRange(location: 0, length: 3))
Run Code Online (Sandbox Code Playgroud)
@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)
| 归档时间: |
|
| 查看次数: |
566 次 |
| 最近记录: |