我正在尝试生成一个基本上只有默认字体、斜体和不同文本颜色的NSAttributedString。到目前为止很简单。
现在,我希望整个字符串的不同子字符串更加粗体。基本上应该是这样的:
从约翰史密斯 25.08。8:00
(只是颜色不同。)
看起来我把字典搞错了,我把它传递给了NSMutableAttributedString的addAttributes(_:_:)函数。从文档,我知道这本字典应该是这样的:
[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谢谢!
发布于 2016-08-25 11:24:17
UIFontDescriptorTraitsAttribute在NSAttributedString属性字典中不是一个可识别的键,因此获得了重建UIFont和使用NSFontAttributeName键所需的特征。
//prepare the fonts. we derive the bold-italic font from the italic font
let italicFont = UIFont.italicSystemFontOfSize(14)
let italicDesc = italicFont.fontDescriptor()
let italicTraits = italicDesc.symbolicTraits.rawValue
let boldTrait = UIFontDescriptorSymbolicTraits.TraitBold.rawValue
let boldItalicTraits = UIFontDescriptorSymbolicTraits(rawValue:italicTraits | boldTrait)
let boldItalicDescriptor = italicDesc.fontDescriptorWithSymbolicTraits(boldItalicTraits)
let boldItalicFont = UIFont(descriptor: boldItalicDescriptor, size: 0.0)
//prepare the string
let rawString = "from John Smith on 25.08. at 8:00"
let attributedString = NSMutableAttributedString(string: rawString)
let fullRange = NSMakeRange(0, 33)
let nameRange = (rawString as NSString).rangeOfString("John Smith")
attributedString.addAttributes([NSFontAttributeName:italicFont], range: fullRange)
attributedString.addAttributes([NSFontAttributeName:boldItalicFont], range: nameRange)https://stackoverflow.com/questions/39141555
复制相似问题