安装
Pods
pod 'LocalizedSwift'
Swift 包管理器
从 Xcode 中选择 File → Swift Packages → Add Package Dependency → 选择您的项目 → 搜索 LocalizedSwift
使用方法
可以在符合 Localizable
协议的类中本地化字符串,在组件声明前添加 @Localized("YouKey")
。`UILabel`、`UIButton`、`UITextField` 和 `UIImageView` 已经符合 Localizable
协议。
// In the following example the string for the key "Label.Title" will be searched in the file "Localizable.strings".
@Localized("Label.Title")
@IBOutlet private var label: UILabel!
如果字符串定义在不同的文件中,不是 Localizable.strings
,则设置参数 stringsFileName
为文件名。
// In the following example the string for the key "Label.Title" will be searched in the file "AFile.strings".
@Localized("Label.Title", stringsFileName: "AFile")
@IBOutlet private var label: UILabel!
如果 .strings
文件在各不同的 .main
包中,设置参数 bundle
为包含该文件的打包。
// In the following example the string for the key "Label.Title" will be searched in the file "AFile.strings" in the bundle `.anotherBundle`.
@Localized("Label.Title", stringsFileName: "AFile", bundle: .anotherBundle)
@IBOutlet private var label: UILabel!
设置状态字符串
可以使用声明 @Localized(.key(, for:), .key(, for:) ..., stringsFileName:, bundle:)
来为不同的 UIControl.State
设置不同的本地化字符串。
方法 .key(:, for: )
是一个工厂方法,用于实例化与状态 LocalizedConfiguration
关联的对象。
// In the following example the string for the key "Button.Title" will be set for the normal state and the string for the key "Button.Highlighted.Title" will be set for the highlighted state.
@Localized(.key("Button.Title", for: .normal),
.key("Button.Highlighted.Title", for: .highlighted))
@IBOutlet private var button: UIButton!
和上述示例一样,可以设置 stringsFileName
和 bundle
。
信息
制作