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

如何利用NSProgress的localizedAdditionalDescription显示“10个文件中的3个”

解决NSProgress文件计数本地化描述问题

要实现类似“10个文件中的3个”的本地化进度描述,核心是避开kind = .file的字节数默认行为,直接自定义本地化字符串或配置正确的单位信息,以下是两种可行方案:

方案一:直接自定义本地化描述(推荐)

通过设置ProgressUserInfoKey.localizedAdditionalDescriptionKey,用本地化字符串格式化文件计数,完全匹配需求的显示格式:

let totalFiles = 15
let completedFiles = 10

let progress = Progress(totalUnitCount: Int64(totalFiles))
progress.completedUnitCount = Int64(completedFiles)

// 配置主描述(可选,显示当前操作)
let mainDescription = String.localizedStringWithFormat(
    NSLocalizedString("Processing %lu files…", comment: "主进度描述"),
    totalFiles
)
progress.setUserInfoObject(mainDescription, forKey: .localizedDescriptionKey)

// 配置附加描述,实现“X个文件中的Y个”格式
let additionalDescription = String.localizedStringWithFormat(
    NSLocalizedString("%lu of %lu files", comment: "文件计数进度描述"),
    completedFiles,
    totalFiles
)
progress.setUserInfoObject(additionalDescription, forKey: .localizedAdditionalDescriptionKey)

// 中文环境下输出
print(progress.localizedDescription) // 正在处理15个文件…
print(progress.localizedAdditionalDescription) // 15个文件中的10个

补充:本地化字符串配置

在项目的中文Localizable.strings文件中添加对应翻译:

"Processing %lu files…" = "正在处理%lu个文件…";
"%lu of %lu files" = "%2$lu个文件中的%1$lu个";

方案二:利用NSProgress单位本地化

如果希望依赖NSProgress的自动单位处理,可配置单位名称的本地化键,让系统自动生成带单位的计数描述:

let totalFiles = 15
let completedFiles = 10

let progress = Progress(totalUnitCount: Int64(totalFiles))
progress.completedUnitCount = Int64(completedFiles)
progress.kind = .none

// 设置单位的单复数本地化
progress.setUserInfoObject(NSLocalizedString("file", comment: "文件单位单数"), forKey: .localizedUnitNameKey)
progress.setUserInfoObject(NSLocalizedString("files", comment: "文件单位复数"), forKey: .localizedUnitsKey)

// 中文环境下输出
print(progress.localizedDescription) // 25% 已完成
print(progress.localizedAdditionalDescription) // 10 of 15 文件

关键说明

  • 当kind = .file时,NSProgress默认将totalUnitCount和completedUnitCount解析为字节数,这就是你之前测试出现字节数描述的原因。
  • 若仅跟踪文件数量进度,无需设置kind = .file,保持默认.none即可,再通过自定义本地化字符串或单位配置实现需求格式。

内容的提问来源于stack exchange,提问作者Marek H

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 17:05:18