总和的 UILabel 问题

UILabel issue with sum

我的UILabel文本很长(不同情况和语言文本不同,我用的是AttributedString),以amount结尾。像:

This amount will be taken from your account: 12.00 $

标签有 numberOfLines = 0,所以有时文字看起来像

This amount will be taken from your account: 12.00 
$

而且不要在 12.00 和 $ 之间设置换行符非常重要,因为它看起来很糟糕。有没有什么特殊符号比如   在 html 中,所以我可以把它放在 12.00 和 $ 之间?所以 UILabel 永远不会在 12 和 $?

之间插入 break

所以我想要的是:

This amount will be taken from your account: 
12.00 $

This amount will be taken from your account: 12.00 $

This amount will be taken from 
your account: 12.00 $

但绝不会像

This amount will be taken from your account: 12.00 
$

Are there any special symbol like   in html, so I can put it between 12.00 and $ ?

对于这种情况,您可以使用 nobreak space 字符 \u00a0

示例:

let text = "This amount will be taken from your account: 12.00\u{00a0}$"

因此请确保您没有对标签设置高度限制,然后执行此操作。

var value = 12.00
yourLabel.numberOfLines = 0
yourLabel.text = "This amount will be taken from your account: \n \(value) $"

您可以添加 non-breaking unicode space 字符,但是,您的操作是错误的。

您应该使用 NSNumberFormatter,样式设置为 .currencycurrencyCode 设置为 USD

那会给你:

  1. 不中断space自动
  2. 所有语言的正确格式(即英语中的 .00,英语中的负数 $(12.00),欧洲区域设置中的 12.00 US$)。

请注意,我标记了一个重复的问题。

duplicated question, you need to use the "No-Break Space" unicode character "\u00a0"所述。

我想建议你可能想使用 NumberFormatter 来处理货币字符,类似于:

let formatter = NumberFormatter()
formatter.numberStyle = .currency
if let amount = formatter.string(from: 12.0 as NSNumber) {
    print(amount) // .00
}