2017-09-25 64 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

相關問題