嗨,我有一個字串,我在標簽中顯示這樣"4hours 27mins 45secs"的時間,例如,這可能因時間而異"30mins 5secs"
我想對字串中的 Ints 進行樣式設定,使它們變粗,字符變亮,所以看起來像這樣......

我進行了一些搜索,發現我需要使用某種屬性字串,但我發現的所有內容似乎都使用某種破壞字符或標準前綴來檢測。
因為我沒有,所以有辦法檢查字符是否為 int 并應用粗體。欣賞這可能是不可能的,并歡迎提出改變我的方法的建議。
對編碼/swift仍然很陌生,所以任何幫助表示贊賞!
uj5u.com熱心網友回復:
快速完成,您可以使用正則運算式來查找所有數字的范圍。然后,在這些范圍內,您更改粗體字體的屬性。
let attributedString = NSMutableAttributedString(string: str, attributes: [.foregroundColor: UIColor.white])
let regex = try! NSRegularExpression(pattern: "\\d ", options: [])
let matches = regex.matches(in: attributedString.string, options: [], range: NSRange(location: 0, length: attributedString.length))
matches.forEach {
attributedString.addAttributes([.font: UIFont.boldSystemFont(ofSize: 17)], range: $0.range)
}
uj5u.com熱心網友回復:
如果你的部署目標是 iOS15,你可以使用新添加AttributedString的 markdown 支持,這比使用非常復雜的NSAttributedString.
https://developer.apple.com/documentation/foundation/attributedstring
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/415446.html
標籤:
