簡體   English   中英

為什么在 iOS 13 上更改 UILabel 的文本不會重置文本屬性?

[英]Why does changing the text of a UILabel not reset text attributes on iOS 13?

在 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.

您沒有重置attributedText ,但文檔說 -如果設置,標簽將忽略上面的屬性(請參閱下面的UILabel.h界面,在 obj-c 中它更正確可見):

@property(null_resettable, nonatomic,strong) UIColor     *textColor UI_APPEARANCE_SELECTOR; // default is labelColor
...

// the underlying attributed string drawn by the label, if set, the label ignores the properties above.
@property(nullable, nonatomic,copy)   NSAttributedString *attributedText API_AVAILABLE(ios(6.0));  // default is nil

所以按照指定的方式運行(之前它可能是一個錯誤,現在已修復)

您的情況的解決方案應該是

label.attributedText = attributedString        
...
label.attributedText = nil      // << reset to default !!
label.text = "What's up world"

好像從 iOS 13 開始,如果你設置並屬性到整個 text ,它就會持續存在! 如果您不在整個文本范圍內應用該屬性,它的行為與以前一樣。

你有一些選擇來解決它:

  1. 沒有在整個范圍內應用它(大多數時候發生):
attributedString.addAttributes([
    .foregroundColor: UIColor.red,
    .backgroundColor: UIColor.green
], range: NSRange(location: 0, length: 3))
  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
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM