You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift技术问题:如何在本地化字符串中用图片替换%1$s占位符?

问题原因及解决方案

问题根源

你的代码存在两个核心问题:

  1. 直接操作mutableString替换无效:NSMutableAttributedString的mutableString仅负责管理纯文本内容,而你要替换的是富文本附件,纯文本替换逻辑无法识别并插入附件类型内容。
  2. logoImageString.string是空值:带有NSTextAttachment的富文本,其string属性不会包含任何有效内容,所以替换操作相当于把%1$s换成空字符串,自然看不到图片效果。

正确实现代码

// 1. 获取本地化字符串
let localizedText = NSLocalizedString("your_localization_key", comment: "")
let myString = NSMutableAttributedString(string: localizedText)

// 2. 创建并配置图片附件(设置bounds保证和文字对齐)
let logoAttachment = NSTextAttachment()
if let logoImage = UIImage(named: "myLogoImage") {
    let targetFont = myFont
    // 根据字体高度调整图片位置,避免和文字错位
    logoAttachment.image = logoImage
    logoAttachment.bounds = CGRect(
        x: 0,
        y: (targetFont.capHeight - logoImage.size.height) / 2,
        width: logoImage.size.width,
        height: logoImage.size.height
    )
}

// 3. 构建带附件的富文本
let logoImageString = NSAttributedString(attachment: logoAttachment)

// 4. 定位占位符范围并执行替换
let placeholder = "%1$s"
if let range = myString.string.range(of: placeholder) {
    let nsRange = NSRange(range, in: myString.string)
    myString.replaceCharacters(in: nsRange, with: logoImageString)
}

// 5. 设置标签属性
myLabel.attributedText = myString
myLabel.font = myFont
myLabel.textColor = myColor

关键说明

  • 必须使用NSMutableAttributedString的replaceCharacters(in:with:)方法,才能将指定范围的文本替换为带附件的富文本。
  • 配置NSTextAttachment的bounds是必要操作,否则图片可能和文字基线错位(偏高或偏低)。
  • 先获取本地化字符串再构建富文本,确保多语言场景下占位符位置变化时仍能正确匹配替换。

内容的提问来源于stack exchange,提问作者I Don't Tell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 21:25:26