SomeGuy
SomeGuy

Reputation: 3845

In Swift, how can I change an attribute of part of a string?

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!

Upvotes: 0

Views: 200

Answers (1)

Vini App
Vini App

Reputation: 7485

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

Upvotes: 1

Related Questions