[英]NSMutableAttributedString to know where color is changed on which text
[英]NSMutableAttributedString text color not working correctly
我有以下 swift 4.1 代碼:
let timeduration = NSMutableAttributedString.init(string: "a dynamic string of time");
timeduration.addAttribute(kCTFontAttributeName as NSAttributedStringKey, value: UIFont.systemFont(ofSize: 16), range: NSRange(location: 0, length: timeduration.length));
timeduration.addAttribute(kCTForegroundColorAttributeName as NSAttributedStringKey, value: UIColor(red: 200/255, green: 200/255, blue: 200/255, alpha: 1.0), range: NSRange(location: 0, length: timeduration.length));
timeduration.addAttribute(kCTFontAttributeName as NSAttributedStringKey, value: UIFont.systemFont(ofSize: 50), range: NSRange(location: 0, length: timecount));
timeduration.addAttribute(kCTFontAttributeName as NSAttributedStringKey, value: UIFont.systemFont(ofSize: 25), range: NSRange(location: timecount, length: 2));
我使用的是 Swift 3 並使用 Xcode 的工具遷移到 swift 4.1,但前景色似乎不起作用。 XCode 工具“修復”添加了 kCT 代碼。 字體名稱和大小似乎可以正常工作。
這是您的問題的解決方案。 在 Swift 4.0 及更高版本中,有一個名為 NSAttributedStringKey 的結構,它定義了字符串屬性的鍵。
let timeduration = NSMutableAttributedString.init(string: "a dynamic string of time")
timeduration.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 16), range: NSRange(location: 0, length: timeduration.length))
timeduration.addAttribute(NSAttributedStringKey.foregroundColor, value:
UIColor(red: 200/255, green: 200/255, blue: 200/255, alpha: 1.0), range:
NSRange(location: 0, length: timeduration.length))
timeduration.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 50), range: NSRange(location: 0, length: timecount))
timeduration.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 25), range: NSRange(location: timecount, length: 2))
fixit 給了你錯誤的鍵。 你想改用這樣的東西:
timeduration.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: NSRange(location: 0, length: timeduration.length))
所有其他人也是如此。
您使用的鍵用於較低級別的核心文本內容。
你可以這樣做,我希望問題能得到解決:-
let label = UILabel()
let labelText = "String Text"
let strokeTextAttributes = [
NSAttributedStringKey.strokeColor : UIColor.black,
NSAttributedStringKey.foregroundColor : UIColor.white,
NSAttributedStringKey.strokeWidth : -2.0,
NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18)
] as [NSAttributedStringKey : Any]
label.attributedText = NSAttributedString(string: labelText, attributes: strokeTextAttributes)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.