我试图生成一个NSAttributedString
基本上只有默认字体,是斜体和不同的文字颜色。足够简单,到目前为止。NSAttributedString与UIFontWeightTraits
现在我想要这整个字符串的不同子串到另外要粗体。它应该基本看起来像这样:
从约翰史密斯于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
谢谢!
你必须采取多种属性字符串合并到一个显示。 –
你的意思是在使用上面提到的功能之后,我不能再添加其他的? – flohei