我從我的回復中收到一條訊息,比如“你的賬單是:10.00”
但是我需要以粗體顯示數字,并且僅顯示該數字(“:”之后的所有內容)。我知道我可以使用 SubString,但不明白如何拆分文本并正確格式化它
我的舊測驗:
self.disclaimerLabel.attributedText = String(format: my).htmlAttributedString(withBaseFont: Font.overlineRegular07.uiFont, boldFont: Font.overlineBold02.uiFont, baseColor: Color.blueyGreyTwo.uiColor, boldColor: Color.blueyGreyTwo.uiColor)
uj5u.com熱心網友回復:
是如何my建造的?如果來自 2 個部分,則在加入之前為每個部分設定屬性。
如果你my作為一個整體,你可以訪問子字串
let parts = my.split(separator: ":")
零件 [1] 將是“您的賬單是”零件 [2] 將是“10:00”
uj5u.com熱心網友回復:
為單個單詞或短語添加樣式的需求非常普遍,因此值得擁有一種方法來幫助您:
extension NSMutableAttributedString {
func apply(attributes: [NSAttributedString.Key: Any], to targetString: String) {
let nsString = self.string as NSString
let range = nsString.range(of: targetString)
guard range.length != 0 else { return }
self.addAttributes(attributes, range: range)
}
}
因此,您唯一的問題是發現要應用屬性的文本段。如果您不知道它是"10.00"那么,正如您被告知的那樣,您可以通過在冒號加空格處拆分字串來找出答案。
uj5u.com熱心網友回復:
您可以將字串拆分為字符:,然后可以更改文本屬性,例如:
var str = "your bill is: 10.00"
var splitArray = str.components(separatedBy: ":")
let normalText = NSMutableAttributedString(string: splitArray[0] ":")
let boldText = splitArray[1]
let boldTextAtr = NSMutableAttributedString(string: boldText, attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16.0) ])
normalText.append(boldTextAtr)
let labell = UILabel()
labell.attributedText = normalText
labell.attributedText 將列印您真正想要的內容
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/349202.html
