在 Swift 中,如何更改部分字符串的属性? [英] In Swift, how can I change an attribute of part of a string?

查看:59
本文介绍了在 Swift 中,如何更改部分字符串的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用一些文本显示分数.分数显示在句子的中间,我希望分数的字体比其余文本大.

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.

我的代码如下:

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

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!

推荐答案

请检查:

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

这篇关于在 Swift 中,如何更改部分字符串的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆