我想要在Xcode Playground上更改地区以测试本地化。
我找到了这个解决方案,但它不适用于Xcode 6.3.2 Playground: http://natashatherobot.com/locale-playground-swift/
我找到了这个解决方案,但它不适用于Xcode 6.3.2 Playground: http://natashatherobot.com/locale-playground-swift/
哦,我找到了一个解决方案!
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)
编辑: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
如果想要在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)
输出:
£12,345.67
注意:它也可用于单元测试。
#selector
语法。https://swift.org/blog/swift-2-2-new-features/ - Jessedc