Xcode 14本地化字符串问题:UILabel文本全粗体需部分加粗
解决方案
不需要为每种语言创建独立storyboard,以下几种简便方法可以解决你的问题,且不会影响应用性能:
方法1:在本地化字符串中嵌入标记,解析为富文本
在Localizable.strings文件中,用自定义标记(比如**)包裹需要加粗的内容,然后通过代码解析这些标记,生成带样式的NSAttributedString。
步骤:
在各语言的
Localizable.strings中添加带标记的文本:
英文版本:"long_content" = "Regular text **bolded content** regular text again.";中文版本:
"long_content" = "普通文本**需要加粗的内容**回到普通文本。";编写解析工具方法:
func parseLocalizedAttributedString(key: String, fontSize: CGFloat = 17) -> NSAttributedString { let rawText = NSLocalizedString(key, comment: "") let regexPattern = "\\*\\*(.*?)\\*\\*" let regex = try! NSRegularExpression(pattern: regexPattern, options: []) let mutableAttrStr = NSMutableAttributedString(string: rawText) // 设置默认字体 let defaultFont = UIFont.systemFont(ofSize: fontSize) mutableAttrStr.addAttribute(.font, value: defaultFont, range: NSRange(location: 0, length: rawText.count)) // 倒序处理匹配结果,避免修改字符串后range偏移 let matches = regex.matches(in: rawText, options: [], range: NSRange(location: 0, length: rawText.count)).reversed() for match in matches { // 获取加粗内容的range let contentRange = match.range(at: 1) // 设置粗体字体 let boldFont = UIFont.boldSystemFont(ofSize: fontSize) mutableAttrStr.addAttribute(.font, value: boldFont, range: contentRange) // 移除前后的**标记 mutableAttrStr.deleteCharacters(in: NSRange(location: match.range.upperBound - 2, length: 2)) mutableAttrStr.deleteCharacters(in: NSRange(location: match.range.lowerBound, length: 2)) } return mutableAttrStr }
- 在代码中给UILabel赋值:
yourLabel.attributedText = parseLocalizedAttributedString(key: "long_content")
方法2:拆分本地化文本片段,拼接富文本
把需要不同样式的文本拆分为独立的本地化键,然后在代码中分别设置样式并拼接。
步骤:
在
Localizable.strings中拆分文本:
英文版本:"content_normal_start" = "Regular text "; "content_bold" = "bolded content"; "content_normal_end" = " regular text again.";中文版本:
"content_normal_start" = "普通文本 "; "content_bold" = "需要加粗的内容"; "content_normal_end" = " 回到普通文本。";代码中拼接富文本:
let normalStart = NSLocalizedString("content_normal_start", comment: "") let boldText = NSLocalizedString("content_bold", comment: "") let normalEnd = NSLocalizedString("content_normal_end", comment: "") let attrStr = NSMutableAttributedString() // 添加普通文本 attrStr.append(NSAttributedString(string: normalStart, attributes: [.font: UIFont.systemFont(ofSize: 17)])) // 添加加粗文本 attrStr.append(NSAttributedString(string: boldText, attributes: [.font: UIFont.boldSystemFont(ofSize: 17)])) // 添加剩余普通文本 attrStr.append(NSAttributedString(string: normalEnd, attributes: [.font: UIFont.systemFont(ofSize: 17)])) yourLabel.attributedText = attrStr
方法3:利用Xcode的Attributed String本地化(Xcode 14支持)
在storyboard或xib中,给UILabel设置Attributed Text,然后在Xcode的本地化面板中直接翻译带样式的文本:
- 选中UILabel,在Attributes Inspector中设置Attributed Text,标记需要加粗的部分。
- 打开Xcode的Localizations设置,确保目标语言已添加。
- 找到该storyboard/xib的本地化文件,直接编辑对应语言的Attributed Text内容,保留样式。
这种方法无需编写额外代码,但需要在本地化文件中维护富文本格式,适合样式固定的场景。
所有方法都无需创建多语言storyboard,性能开销远低于多storyboard方案,完全不用担心应用变慢。
内容的提问来源于stack exchange,提问作者wiwihello
相关产品推荐
相关产品推荐

