ios Swift 中的 NSLocalizedString 等价物是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25081757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:39:04  来源:igfitidea点击:

What's NSLocalizedString equivalent in Swift?

iosswiftlocalizationnslocalizedstring

提问by RaffAl

Is there an Swift equivalent of NSLocalizedString(...)? In Objective-C, we usually use:

是否有 Swift 等价物NSLocalizedString(...)?在Objective-C,我们通常使用:

NSString *string = NSLocalizedString(@"key", @"comment");

How can I achieve the same in Swift? I found a function:

如何在 Swift 中实现相同的目标?我找到了一个函数:

func NSLocalizedString(
    key: String,
    tableName: String? = default,
    bundle: NSBundle = default,
    value: String = default,
    #comment: String) -> String

However, it is very long and not convenient at all.

但是,它很长,一点也不方便。

回答by dr OX

I use next solution:

我使用下一个解决方案:

1) create extension:

1)创建扩展:

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

2) in Localizable.stringsfile:

2) 在Localizable.strings文件中:

"Hi" = "Привет";

3) example of use:

3) 使用示例:

myLabel.text = "Hi".localized

enjoy! ;)

请享用!;)

--upd:--

--更新:--

for case with comments you can use this solution:

对于有评论的情况,您可以使用此解决方案:

1) Extension:

1) 扩展:

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

2) in .strings file:

2) 在 .strings 文件中:

/* with !!! */
"Hi" = "Привет!!!";

3) using:

3)使用:

myLabel.text = "Hi".localized(withComment: "with !!!")

回答by RaffAl

The NSLocalizedStringexists also in the Swift's world.

NSLocalizedString在斯威夫特的世界同样存在。

func NSLocalizedString(
    key: String,
    tableName: String? = default,
    bundle: NSBundle = default,
    value: String = default,
    #comment: String) -> String

The tableName, bundle, and valueparameters are marked with a defaultkeyword which means we can omit these parameters while calling the function. In this case, their default values will be used.

tableNamebundlevalue参数均标有default该装置的同时调用该函数我们可以忽略这些参数的关键字。在这种情况下,将使用它们的默认值。

This leads to a conclusion that the method call can be simplified to:

由此得出结论,方法调用可以简化为:

NSLocalizedString("key", comment: "comment")

Swift 5- no change, still works like that.

Swift 5- 没有变化,仍然如此。

回答by José

A variation of the existing answers:

现有答案的变体:

Swift 5.1:

斯威夫特 5.1:

extension String {

    func localized(withComment comment: String? = nil) -> String {
        return NSLocalizedString(self, comment: comment ?? "")
    }

}

You can then simply use it with or without comment:

然后,您可以在有或没有评论的情况下简单地使用它:

"Goodbye".localized()
"Hello".localized(withComment: "Simple greeting")

Please notethat genstringswon't work with this solution.

请注意genstrings这不适用于此解决方案。

回答by Kay

By using this way its possible to create a different implementation for different types (i.e. Int or custom classes like CurrencyUnit, ...). Its also possible to scan for this method invoke using the genstrings utility. Simply add the routine flag to the command

通过使用这种方式,可以为不同类型(即 Int 或自定义类,如 CurrencyUnit 等)创建不同的实现。也可以使用 genstrings 实用程序扫描此方法调用。只需将例程标志添加到命令中

genstrings MyCoolApp/Views/SomeView.swift -s localize -o .

extension:

延期:

import UIKit

extension String {
    public static func localize(key: String, comment: String) -> String {
        return NSLocalizedString(key, comment: comment)
    }
}

usage:

用法:

String.localize("foo.bar", comment: "Foo Bar Comment :)")

回答by Jan

Swift 3 version :)...

斯威夫特 3 版本 :)...

import Foundation

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

回答by JOM

Created a small helper method for cases, where "comment" is always ignored. Less code is easier to read:

为始终忽略“注释”的情况创建了一个小的辅助方法。更少的代码更容易阅读:

public func NSLocalizedString(key: String) -> String {
    return NSLocalizedString(key, comment: "")
}

Just put it anywhere (outside a class) and Xcode will find this global method.

只要把它放在任何地方(在类之外),Xcode 就会找到这个全局方法。

回答by GYFK

Actually, you can use two phases to translate your texts in Swift projects:

实际上,您可以使用两个阶段来翻译 Swift 项目中的文本:

1) The first phase is using the old way to create all your translatable strings:

1) 第一阶段是使用旧方法创建所有可翻译字符串:

NSLocalisedString("Text to translate", comment: "Comment to comment")

1.1) Then you should use genstrings to generate Localizable.strings:

1.1) 那么你应该使用 genstrings 来生成 Localizable.strings:

$ genstrings *swift

2) Afterwards, you should use this answer.

2)之后,你应该使用这个答案

2.1) Use your XCode "Find and Replace" option based on the regular expression. As for the given example (if you have no comments) the regular expression will be:

2.1)根据正则表达式使用您的XCode“查找和替换”选项。至于给定的例子(如果你没有评论)正则表达式将是:

NSLocalizedString\((.*)\, comment:\ \"\"\) 

and replace it with

并将其替换为

.localized

or (if you have comments)

或(如果您有意见)

NSLocalizedString\((.*)\, comment:\ (.*)\)

and replace it with

并将其替换为

.localizedWithComment(comment: )

You are free to play with regex and different extension combinations as you wish. The general way is splitting the whole process in two phases. Hope that helps.

您可以随意使用正则表达式和不同的扩展组合。一般的方法是将整个过程分为两个阶段。希望有帮助。

回答by Robin Dorpe

Probably the best way is this one here.

可能最好的方法是这里的这个。

fileprivate func NSLocalizedString(_ key: String) -> String {
    return NSLocalizedString(key, comment: "")
}

and

import Foundation
extension String {
    static let Hello = NSLocalizedString("Hello")
    static let ThisApplicationIsCreated = NSLocalizedString("This application is created by the swifting.io team")
    static let OpsNoFeature = NSLocalizedString("Ops! It looks like this feature haven't been implemented yet :(!")
}

you can then use it like this

然后你可以像这样使用它

let message: String = .ThisApplicationIsCreated
print(message)

to me this is the best because

对我来说这是最好的,因为

  • The hardcoded strings are in one specific file, so the day you want to change it it's really easy
  • Easier to use than manually typing the strings in your file every time
  • genstrings will still work
  • you can add more extensions, like one per view controller to keep things neat
  • 硬编码的字符串在一个特定的文件中,所以你想改变它的那一天真的很容易
  • 比每次手动输入文件中的字符串更容易使用
  • genstrings 仍然有效
  • 您可以添加更多扩展,例如每个视图控制器一个以保持整洁

回答by Liam

When you are developing an SDK. You need some extra operation.

当您开发 SDK 时。你需要一些额外的操作。

1) create Localizable.stringsas usual in YourLocalizeDemoSDK.

1)像往常一样在 YourLocalizeDemoSDK 中创建Localizable.strings

2) create the same Localizable.stringsin YourLocalizeDemo.

2)在 YourLocalizeDemo 中创建相同的Localizable.strings

3) find your Bundle Pathof YourLocalizeDemoSDK.

3) 找到您的 YourLocalizeDemoSDK的捆绑路径

Swift4:

斯威夫特4

// if you use NSLocalizeString in NSObject, you can use it like this
let value = NSLocalizedString("key", tableName: nil, bundle: Bundle(for: type(of: self)), value: "", comment: "")

Bundle(for: type(of: self))helps you to find the bundle in YourLocalizeDemoSDK. If you use Bundle.maininstead, you will get a wrong value(in fact it will be the same string with the key).

Bundle(for: type(of: self))帮助您在 YourLocalizeDemoSDK 中找到包。如果你Bundle.main改用,你会得到一个错误的值(实际上它将是与键相同的字符串)。

But if you want to use the String extension mentioned by dr OX. You need to do some more. The origin extension looks like this.

但是,如果您想使用OX 博士提到的 String 扩展名。你需要做更多的事情。原点扩展看起来像这样。

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

As we know, we are developing an SDK, Bundle.mainwill get the bundle of YourLocalizeDemo's bundle. That's not what we want. We need the bundle in YourLocalizeDemoSDK. This is a trick to find it quickly.

我们知道,我们正在开发一个SDK,Bundle.main会得到YourLocalizeDemo的bundle。那不是我们想要的。我们需要 YourLocalizeDemoSDK 中的包。这是一个快速找到它的技巧。

Run the code below in a NSObject instance in YourLocalizeDemoSDK. And you will get the URL of YourLocalizeDemoSDK.

在 YourLocalizeDemoSDK 的 NSObject 实例中运行以下代码。您将获得 YourLocalizeDemoSDK 的 URL。

let bundleURLOfSDK = Bundle(for: type(of: self)).bundleURL
let mainBundleURL = Bundle.main.bundleURL

Print both of the two url, you will find that we can build bundleURLofSDK base on mainBundleURL. In this case, it will be:

打印两个url,你会发现我们可以在mainBundleURL的基础上构建bundleURLofSDK。在这种情况下,它将是:

let bundle = Bundle(url: Bundle.main.bundleURL.appendingPathComponent("Frameworks").appendingPathComponent("YourLocalizeDemoSDK.framework")) ?? Bundle.main

And the String extension will be:

而字符串扩展将是:

extension String {
    var localized: String {
        let bundle = Bundle(url: Bundle.main.bundleURL.appendingPathComponent("Frameworks").appendingPathComponent("YourLocalizeDemoSDK.framework")) ?? Bundle.main
        return NSLocalizedString(self, tableName: nil, bundle: bundle, value: "", comment: "")
    }
}

Hope it helps.

希望能帮助到你。

回答by Max

I've created my own genstrings sort of tool for extracting strings using a custom translation function

我已经创建了自己的 genstrings 类工具,用于使用自定义翻译函数提取字符串

extension String {

    func localizedWith(comment:String) -> String {
        return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: comment)
    }

}

https://gist.github.com/Maxdw/e9e89af731ae6c6b8d85f5fa60ba848c

https://gist.github.com/Maxdw/e9e89af731ae6c6b8d85f5fa60ba848c

It will parse all your swift files and exports the strings and comments in your code to a .strings file.

它将解析您所有的 swift 文件并将代码中的字符串和注释导出到 .strings 文件。

Probably not the easiest way to do it, but it is possible.

可能不是最简单的方法,但它是可能的。