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

Swift:如何本地化由Double变量控制复数的Stepper标题?

解决Stepper本地化的小数格式与复数规则冲突问题

1. 正确配置Localizable.stringsdict

在Localizable.stringsdict中同时定义复数规则和数字格式,避免单独格式化数字导致复数失效的问题。以下是适配需求的配置内容:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>sleep_duration</key>
    <dict>
        <key>NSStringLocalizedFormatKey</key>
        <string>%#@hours@</string>
        <key>hours</key>
        <dict>
            <key>NSStringFormatSpecTypeKey</key>
            <string>NSStringPluralRuleType</string>
            <key>NSStringFormatValueTypeKey</key>
            <string>f</string>
            <key>one</key>
            <string>%.0f hour</string>
            <key>other</key>
            <string>%.2f hours</string>
        </dict>
    </dict>
</dict>
</plist>
  • NSStringFormatValueTypeKey设为f,表示接收浮点型数值(double/float),符合复数规则的类型要求
  • one分支使用%.0f,确保数值为1时显示整数格式1 hour
  • other分支使用%.2f,让小数数值显示两位小数,如1.25 hours、3.50 hours

2. 在SwiftUI中调用本地化字符串

直接传递原始的sleepAmount(Double类型)给本地化方法,无需提前格式化字符串:

struct ContentView: View {
    @State private var sleepAmount = 1.0
    
    var body: some View {
        Stepper(
            String.localizedStringWithFormat(NSLocalizedString("sleep_duration", comment: "Sleep duration"), sleepAmount),
            value: $sleepAmount,
            step: 0.25
        )
    }
}

关键说明

  • 避免提前将Double转为字符串:复数规则仅支持数值类型(int/double/float),传入字符串会导致复数判断失效,出现1.25 hour这类错误
  • 利用stringsdict的格式控制:通过%.0f和%.2f直接在本地化规则中处理数字格式,既满足显示需求,又保留数值类型供复数判断使用

内容的提问来源于stack exchange,提问作者Tuan Pham

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 07:35:28