【发布时间】:2016-08-25 19:31:29
【问题描述】:
我正在尝试生成一个基本上只有默认字体、斜体和不同文本颜色的NSAttributedString。很简单,到目前为止。
现在我希望整个字符串的不同子字符串另外加粗。它基本上应该是这样的:
来自 John Smith 于 25.08。 8:00
(只是颜色不同。)
看起来我把字典弄错了,我把它传递给了NSMutableAttributedString 的addAttributes(_:_:) 函数。从documentation,我了解到这本词典应该是这样的:
[UIFontDescriptorTraitsAttribute:
[UIFontWeightTrait: NSNumber(double: Double(UIFontWeightBold))]
但这似乎不起作用。我最终得到的是字符串的斜体版本。我显然在这里弄错了。有什么想法吗?
更新:添加简单示例
// Preparation
let rawString = "from John Smith on 25.08. at 8:00"
let attributedString = NSMutableAttributedString(string: rawString)
let nameRange = (rawString as NSString).rangeOfString("John Smith")
let italicFont = UIFont.italicSystemFontOfSize(14)
// Make entire string italic: works!
attributedString.addAttributes([NSFontAttributeName : italicFont], range: NSMakeRange(0, 33))
// Make the name string additionally bold: doesn't work!
attributedString.addAttributes([UIFontDescriptorTraitsAttribute:
[UIFontWeightTrait: NSNumber(double: Double(UIFontWeightBold))]], range: nameRange)
// Show it on the label
attributedStringLabel.attributedText = attributedString
谢谢!
【问题讨论】:
-
你必须把多个属性字符串组合成一个来显示。
-
你的意思是我不能在使用上述功能后添加额外的?
标签: ios swift nsattributedstring uifont nsmutableattributedstring