[英]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.