【问题标题】:In Swift, how can I change an attribute of part of a string?在 Swift 中,如何更改部分字符串的属性?
【发布时间】:2017-09-25 00:56:36
【问题描述】:

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

我的代码如下:

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

我觉得我在做一些愚蠢的事情,但无法弄清楚它是什么。任何帮助将不胜感激!

【问题讨论】:

标签: ios swift nsattributedstring


【解决方案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

【讨论】:

  • 哇。我尝试按照上面发布的链接进行操作,但它们并没有解决问题。我花了几个小时试图弄清楚这一点,最终发现了 .attributedText 函数。所以我最终完全按照你在这里所说的去做,然后当我回过头来回答我自己的问题时,我找到了你的答案。不管怎么说,还是要谢谢你!我接受了答案。
猜你喜欢
  • 2015-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 2016-05-20
  • 1970-01-01
相关资源
最近更新 更多