在Swift中,如何更改字符串部分的属性?

时间:2017-09-25 00:56:36

标签: ios swift nsattributedstring

我正在尝试用一些文字显示分数。分数显示在句子的中间,我希望分数的字体大于文本的其余部分。

我的代码如下:

let fontSizeAttribute = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 43)]
let myString = String(describing: Int(finalScore!.rounded(toPlaces: 0)))
let attributedString = NSAttributedString(string: myString, attributes: fontSizeAttribute)
scoreLabel.text = "Your score is \(attributedString)%, which is much higher than most people."

我无法看到这个实现有什么问题,但是当我运行它时,它说,"你的分数是9 {NSFont =" UITCFont:0x7f815 ......

我觉得我做了一些愚蠢的事,但却无法弄清楚它是什么。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

请检查:

let fontSizeAttribute = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 43)]
let myString = String(describing: Int(finalScore!.rounded(toPlaces: 0)))

let partOne = NSMutableAttributedString(string: "Your ")
let partTwo = NSMutableAttributedString(string: myString, attributes: fontSizeAttribute)
let partThree = NSMutableAttributedString(string: "%, which is much higher than most people.")

let attributedString = NSMutableAttributedString()

attributedString.append(partOne)
attributedString.append(partTwo)
attributedString.append(partThree)

scoreLabel.attributedText = attributedString