如何在 Swift 中将 NSLocalizedString 函数与变量一起使用?

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

我正在尝试使用

NSLocalizedString
本地化我的应用程序。当我导入 XLIFF 文件时,大多数都像魅力一样工作,但有些则不然,并且某些字符串未本地化。我注意到问题出在
NSLocalizedString
中,其中包含一些变量,例如:

NSLocalizedString(" - \(count) Notifica", comment: "sottotitolo prescrizione per le notifiche al singolare")

NSLocalizedString("Notifica per \(medicina!) della prescrizione \(prescription!)\nMemo: \(memoTextView.text)", comment: "Messaggio della Local Notification")

也许这不是此类内容的正确语法。有人可以解释一下如何在 Swift 中做到这一点吗?

ios swift localization nslocalizedstring xliff
8个回答
164
投票

您可以在

sprintf
中使用
NSLocalizedString
格式参数,因此您的示例如下所示:

let myString = String(format: NSLocalizedString(" - %d Notifica", comment: "sottotitolo prescrizione per le notifiche al singolare"), count)

112
投票

在 WWDC2014“使用 Xcode 6 进行本地化”的第 412 场会议中,在 Swift 中实现此目的的正确方法如下:

String.localizedStringWithFormat(
    NSLocalizedString(" - %d Notifica",
    comment: "sottotitolo prescrizione per le notifiche al singolare"),
    count)

注意

localizedStringWithFormat
根据给定的第一个参数设置返回字符串的
local

  • 不,它不翻译任何东西。
  • 这种混乱来自于
    NSLocalizedString
    的错误命名。
  • 它应该被命名为
    NSTranslatedString
    ,或
    NSTranslatable
    (而不是
    NSLocalizedString
    )。

27
投票

我遵循了创建字符串扩展的方法,因为我有很多字符串需要本地化。

extension String {
    var localized: String {
        return NSLocalizedString(self, comment:"")
    }
}

要在代码中使用它进行本地化,请执行以下操作:

self.descriptionView.text = "Description".localized

对于具有动态变量的字符串,请遵循:

self.entryTimeLabel.text = "\("Doors-open-at".localized) \(event.eventStartTime)"

在字符串文件中声明不同语言的字符串(例如:阿拉伯语和英语)

希望能有所帮助!


16
投票

我尝试了上述解决方案,但是下面的代码对我有用

SWIFT 4

extension String {

    /// Fetches a localized String
    ///
    /// - Returns: return value(String) for key
    public func localized() -> String {
        let path = Bundle.main.path(forResource: "en", ofType: "lproj")
        let bundle = Bundle(path: path!)
        return (bundle?.localizedString(forKey: self, value: nil, table: nil))!
    }


    /// Fetches a localised String Arguments
    ///
    /// - Parameter arguments: parameters to be added in a string
    /// - Returns: localized string
    public func localized(with arguments: [CVarArg]) -> String {
        return String(format: self.localized(), locale: nil, arguments: arguments)
    }

}

// variable in a class
 let tcAndPPMessage = "By_signing_up_or_logging_in,_you_agree_to_our"
                                     .localized(with: [tAndc, pp, signin])

// Localization File String
"By_signing_up_or_logging_in,_you_agree_to_our" = "By signing up or logging in, you agree to our \"%@\" and \"%@\" \nAlready have an Account? \"%@\"";

16
投票

这是我在 String 中使用的扩展,它添加了一个带有可变参数的 localizeWithFormat 函数,

extension String {

     func localizeWithFormat(arguments: CVarArg...) -> String{
        return String(format: self.localized, arguments: arguments)        
     }
            
     var localized: String{
         return Bundle.main.localizedString(forKey: self, value: nil, table: "StandardLocalizations")
     }
}

用途:

let siriCalendarText = "AnyCalendar"
let localizedText = "LTo use Siri with my app, please set %@ as the default list on your device reminders settings".localizeWithFormat(arguments: siriCalendarTitle)

请注意不要使用与 String 相同的函数和属性名称。我通常对所有框架功能使用 3 个字母的前缀。


2
投票

我为

UILabel

编写了相同的函数
extension UILabel {
    
    func setLocalizedText(key: String) {
        self.text = key.localized
    }
    
    func setLocalizedText(key: String, arguments: [CVarArg]) {
        self.text = String(format: key.localized, arguments: arguments)
    }
}

如果您愿意,也可以将此

localized
属性移动到 UILabel

extension String {
        
    var localized: String{
        return Bundle.main.localizedString(forKey: self, value: nil, table: nil)
    }
}

我的本地化

"hi_n" = "Hi, %@!";

像这样使用它们:

self.greetingLabel.setLocalizedText(key: "hi_n", arguments: [self.viewModel.account!.firstName])
// Shows this on the screen -> Hi, StackOverflow!

0
投票

我建议编写一个自定义全局函数而不是扩展,因为

genstrings
只是用文字解析
NSLocalizedString
的源代码。这意味着您将无法使用扩展解决方案从源编码器自动生成
.strings
文件。

func NSLocalizedString(_ key: String, tableName: String? = nil, bundle: Bundle = Bundle.main, value: String = "", comment: String, with arguments: CVarArg...) -> String {
    let localizedString = Foundation.NSLocalizedString(key, tableName: tableName, bundle: bundle, value: value, comment: comment)
    return String.localizedStringWithFormat(localizedString, arguments)
}

-4
投票

我创建了一个

extension
String
,因为我有很多
strings
要成为
localized

extension String {
    var localized: String {
        return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "")
    }
}

例如:

let myValue = 10
let anotherValue = "another value"

let localizedStr = "This string is localized: \(myValue) \(anotherValue)".localized
print(localizedStr)
© www.soinside.com 2019 - 2024. All rights reserved.