[Swift]项目语言国际化

项目语言国际化流程,以作备忘!

1 创建配置文件

工程内新建Strings File文件,并命名Localizable

新建Strings File文件

命名Localizable

创建好后如下图所示

创建后

2 添加语言

选中Localizable.strings文件,点击右侧Localize...

添加语言

点击后如下所示

添加语言

3 设置语言

前往工程PROJECT,点击Localizations下的+

添加语言

在弹出的语言中选择想要使用的语言即可,本次以简体中文英文为例
简体中文为Chinese(Simplified)
英文为English

选择语言

在弹出的窗口上点击Finish即可
有使用Main.storyboardLaunchScreen.storyboard可以勾选这两个

添加语言

完成后就会如下图所示,这两个文件就是当前工程的简体中文英文配置文件

4 简单使用

配置文件填写对应的文字

英文

简体中文

加载对应文字的时候如下

let label = UILabel(frame: CGRect(x: 20, y: 200, width: UIScreen.main.bounds.width - 40, height: 40))
label.backgroundColor = UIColor.lightGray
label.text = NSLocalizedString("国际化语言展示", comment: "")
label.textColor = UIColor.red
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 16)
view.addSubview(label)

模拟器语言为英文和简体中文状态下的展示结果

模拟器语言为英文

模拟器语言为简体中文

5 手动切换语言

创建国际化语言管理工具类

import UIKit

fileprivate let UserLanguage   = "UserLanguage"
fileprivate let AppleLanguages = "AppleLanguages"

enum LanguageType: Int {
    case Chinese = 0
    case English
}

class InternationalTool {

    /// 单例
    static var shared: InternationalTool {
        struct Static {
            static let instance: InternationalTool = InternationalTool()
        }
        return Static.instance
    }
    
    private var bundle: Bundle?
    
    /// 获取国际化语言
    ///
    /// - Parameter key: key
    /// - Returns: 国际化语言
    public func string(_ key: String) -> String {
        let bundle = InternationalTool.shared.bundle
        let str = bundle?.localizedString(forKey: key, value: nil, table: nil)
        return str ?? ""
    }
    
    /// 初始化语言 Appdelegate 中使用
    public func initUserLanguage() {
        var str = UserDefaults.standard.value(forKey: UserLanguage) as? String
        if str?.count == 0 || str == nil {
            let languages = UserDefaults.standard.object(forKey: AppleLanguages) as? NSArray
            if languages?.count != 0 {
                let current = languages?.object(at: 0) as? String
                if current != nil {
                    str = current ?? ""
                    UserDefaults.standard.set(current, forKey: UserLanguage)
                    UserDefaults.standard.synchronize()
                }
            }
        }
        str = str?.replacingOccurrences(of: "-CN", with: "")
        str = str?.replacingOccurrences(of: "-US", with: "")
        var path = Bundle.main.path(forResource: str, ofType: "lproj")
        if path == nil {
            path = Bundle.main.path(forResource: "en", ofType: "lproj")
        }
        bundle = Bundle(path: path!)
    }
    
    /// 设置当前语言
    ///
    /// - Parameter language: 当前语言
    public func setLanguage(_ type: LanguageType) {
        var str = ""
        switch type {
        case .Chinese:
            str = "zh-Hans"
        case .English:
            str = "en"
        }
        let path = Bundle.main.path(forResource: str, ofType: "lproj")
        bundle = Bundle(path: path!)
        UserDefaults.standard.set(str, forKey: UserLanguage)
        UserDefaults.standard.synchronize()
    }
    
    /// 当前语言
    ///
    /// - Returns: 当前语言类型
    public func current() -> String {
        return UserDefaults.standard.value(forKey: UserLanguage) as! String
    }
}

APPdelegate中调用,建议在Window加载前调用,就不会出现因为加载过快导致第一个界面语言没有国际化的现象

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        InternationalTool.shared.initUserLanguage()
        
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.backgroundColor = UIColor.white
        window?.rootViewController = ViewController()
        window?.makeKeyAndVisible()
        
        return true
    }

加载文字时,直接调用工具类的方法即可

label.text = InternationalTool.shared.string("国际化语言展示")

创建界面进行手动切换语言

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let label = UILabel(frame: CGRect(x: 20, y: 200, width: UIScreen.main.bounds.width - 40, height: 40))
        label.backgroundColor = UIColor.lightGray
        label.text = InternationalTool.shared.string("国际化语言展示")
        label.textColor = UIColor.red
        label.textAlignment = .center
        label.font = UIFont.boldSystemFont(ofSize: 16)
        view.addSubview(label)
        
        let button = UIButton(type: .custom)
        button.frame = CGRect(x: 40, y: 260, width: 140, height: 50)
        button.backgroundColor = UIColor.purple
        button.setTitle(InternationalTool.shared.string("英文"), for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.addTarget(self, action: #selector(buttonClick), for: .touchUpInside)
        view.addSubview(button)
        
        let button02 = UIButton(type: .custom)
        button02.frame = CGRect(x: 200, y: 260, width: 140, height: 50)
        button02.backgroundColor = UIColor.purple
        button02.setTitle(InternationalTool.shared.string("中文"), for: .normal)
        button02.setTitleColor(UIColor.white, for: .normal)
        button02.addTarget(self, action: #selector(button02Click), for: .touchUpInside)
        view.addSubview(button02)
    }
    
    @objc func buttonClick(_ sender: UIButton) {
        
        InternationalTool.shared.setLanguage(.English)
        
        UIApplication.shared.keyWindow?.rootViewController = ViewController()
    }
    
    @objc func button02Click(_ sender: UIButton) {
        
        InternationalTool.shared.setLanguage(.Chinese)
        
        UIApplication.shared.keyWindow?.rootViewController = ViewController()
    }
}

具体效果如下

6 App名称国际化

创建Strings File文件,并命名为InfoPlist.strings

选中创建好的文件,点击右侧Localize...

在弹出的窗口中点击Localize

在右侧勾选语言

配置InfoPlist.strings

CFBundleDisplayName = ""

效果如下

你可能感兴趣的:([Swift]项目语言国际化)