2017-09-25 62 views
0

我想显示一些文本的分数。分数显示在一个句子的中间,我希望字体比文本的其余部分更大。在Swift中,如何更改字符串部分的属性?

我的代码如下:

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。 ..

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

+0

你可以在这里找到解决方案。 https://stackoverflow.com/questions/31647653/bold-part-of-string-in-uitextview-swift – HungCLo

+0

你应该设置你的标签属性文本,而不是你的晚期文本属性https://developer.apple.com/documentation/uikit/uilabel/1620542-attributes文字 –

回答

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 
+0

哇。我试着按照上面发布的链接,但他们没有解决问题。我花了数小时试图弄清楚,最终发现了.attributedText函数。所以我最终完全按照你在这里所说的做了,然后当我检查回答我自己的问题时,我找到了你的答案。不管怎么说,还是要谢谢你!我接受了答案。 – SomeGuy

相关问题