简体   繁体   English

如何更改 Xcode 游乐场上的语言环境

[英]How can I change the locale on the Xcode Playground

I'd like to change the locale on the Xcode Playground to test localization.我想更改 Xcode 游乐场上的语言环境以测试本地化。

I found this solution, but it doesn't work on the Xcode 6.3.2 Playground: http://natashatherobot.com/locale-playground-swift/我找到了这个解决方案,但它在 Xcode 6.3.2 游乐场上不起作用: http://natashatherobot.com/locale-playground-swift/

Oh, I've found a solution! 哦,我找到了解决方案!

extension NSLocale {
    class func mono_currentLocale() -> NSLocale {
        return NSLocale(localeIdentifier: "fr")
    }
}
let original = class_getClassMethod(NSLocale.self, #selector(getter: NSLocale.currentLocale))
let swizzled = class_getClassMethod(NSLocale.self, #selector(NSLocale.mono_currentLocale))
method_exchangeImplementations(original, swizzled)

EDIT: Swift 4.1 version: 编辑:Swift 4.1版本:

extension NSLocale {
    @objc class func mono_currentLocale() -> NSLocale {
        return NSLocale(localeIdentifier: "fr")
    }
}
let original = class_getClassMethod(NSLocale.self, #selector(getter: NSLocale.current))!
let swizzled = class_getClassMethod(NSLocale.self, #selector(NSLocale.mono_currentLocale))!
method_exchangeImplementations(original, swizzled)

XCode 13 / Swift 5 XCode 13 / Swift 5

To change the current locale in the playground you can create extension of NSLocale and override currentLocale :要更改 playground 中的当前语言环境,您可以创建NSLocale的扩展并覆盖currentLocale

extension NSLocale {
    @objc
    static let currentLocale = NSLocale(localeIdentifier: "en_GB") // Set a needed locale
}

let formatter = NumberFormatter()
formatter.numberStyle = .currency
let text = formatter.string(from: 12345.67 as NSNumber)!
print(text)

Outputs:输出:

£12,345.67

NOTE: It also works with unit tests.注意:它也适用于单元测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Xcode Playground中使用自动布局约束显示视图? - How can I display views using autolayout constraints in Xcode playground? Xcode 6游乐场—我无法创建OS X游乐场文件 - Xcode 6 playground — I can't create a OS X playground file 如何使用 Swift 以编程方式更改语言环境 - How can I change locale programmatically with Swift 如何在项目目录中的 Xcode 内打开 Playground? - How do I open a Playground inside of Xcode in a project directory? 如何将第三方框架导入Xcode Playground? - How to I import 3rd party frameworks into Xcode Playground? 如何在Playground中编辑描述(而不是代码) - How can I edit description(not code) in Playground 如何在 Swift 5.1(Xcode 11 Playground)中实现可选的通用和非通用 function 签名的重载? - How can I achieve overloading both generic and non-generic function signatures for optionals in Swift 5.1 (Xcode 11 Playground)? 我们可以将xcode项目(xcodeproj)转换为Swift Playground(.playground)格式吗? - Can we convert xcode project (xcodeproj) to swift playground (.playground) format? 如何在Xcode Playground上使用Charles Proxy? - How to use Charles Proxy on an Xcode Playground? 如何在Xcode 9中使用带有游乐场的自定义框架 - How to use a custom framework with a playground in Xcode 9
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM