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

雨燕双飞 提交于 2019-12-12 04:41:51

问题


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!


回答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


来源:https://stackoverflow.com/questions/46396260/in-swift-how-can-i-change-an-attribute-of-part-of-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!