0

I am trying to display a score with some text. The score is displayed in the middle of a sentence, and I want the font to be bigger for the score than the rest of the text.

My code is as follows:

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

I can't see anything wrong with this implementation, but when I run it, it says, "Your score is 9{ NSFont = "UITCFont: 0x7f815...

I feel like I'm doing something stupid, but can't figure out what it is. Any help would be appreciated!

SomeGuy
  • 3,725
  • 3
  • 19
  • 23
  • You can find the solution here. https://stackoverflow.com/questions/31647653/bold-part-of-string-in-uitextview-swift – HungCLo Sep 25 '17 at 01:15
  • You should be setting your label attributedtext instead of your late text property https://developer.apple.com/documentation/uikit/uilabel/1620542-attributedtext – Leo Dabus Sep 25 '17 at 01:33

1 Answers1

1

Please check :

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
Vini App
  • 7,339
  • 2
  • 26
  • 43
  • Wow. I tried following the links that were posted above, and they did not solve the problem. I spent hours trying to figure this out and eventually discovered the .attributedText function. So I ended up doing EXACTLY what you said here, and then when I checked back to answer my own question, I found your answer. Thanks anyway! I accepted the answer. – SomeGuy Sep 25 '17 at 07:06