如何本地化NSMutableAttributedString字符串?

问题描述 投票:0回答:1

你是训练师吗?是普通文本,这里登录是彩色文本。

//下面是我的代码

let string = "Are you a Trainer? Login here"
let plainText: NSRange?     = (string as NSString).range(of: "Are you a Trainer? ")
let plainText1: NSRange?    = (string as NSString).range(of: "Login here")

let attText = NSMutableAttributedString(string: string)

let font: UIFont? = UIFont(name: Fonts.MontserratRegular, size: 14)
let font1: UIFont? = UIFont(name: Fonts.MontserratMedium, size: 16)

attText.setAttributes([NSAttributedString.Key.font: font!, NSAttributedString.Key.foregroundColor: Colors.textFieldPlaceholderColor], range: plainText ?? NSRange())
attText.setAttributes([NSAttributedString.Key.font: font1!, NSAttributedString.Key.foregroundColor: Colors.themeColor], range: plainText1 ?? NSRange())

self.btnLoginAsTrainer.setAttributedTitle(attText, for: .normal)

上面的字符串是NSAttributedString(),现在我想将这个NSAttributedString()本地化为西班牙语。

我怎样才能做到这一点?因此,西班牙字符串显示与英文文本相同的2种文本颜色。

swift localization nsattributedstring
1个回答
0
投票

您可以为一个主字符串创建本地化

"main_string" = "Are you a Trainer? Login here";

然后你可以为子串创建本地化

"substring1" =  "Are you a Trainer?";
"substring2" = " Login here";

然后在substring1找到main_string的范围并设置你的属性。


这是您找到范围并将其应用于属性字符串的方法

            let stringFinal = NSLocalizedString("main_string", comment: "")
            let substringOne = NSLocalizedString("substring1", comment: "")

            let range = stringFinal.range(of: substringOne)
            let substringRange = NSRange.init(range!, in: stringFinal)
            let attribute = NSMutableAttributedString.init(string: stringFinal)
            attribute.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.gray , range: substringRange)
© www.soinside.com 2019 - 2024. All rights reserved.