[Swift]項(xiàng)目語言國際化

項(xiàng)目語言國際化流程,以作備忘!

1 創(chuàng)建配置文件

工程內(nèi)新建Strings File文件,并命名Localizable

新建Strings File文件

命名Localizable

創(chuàng)建好后如下圖所示

創(chuàng)建后

2 添加語言

選中Localizable.strings文件,點(diǎn)擊右側(cè)Localize...

添加語言

點(diǎn)擊后如下所示

添加語言

3 設(shè)置語言

前往工程PROJECT,點(diǎn)擊Localizations下的+

添加語言

在彈出的語言中選擇想要使用的語言即可,本次以簡體中文英文為例
簡體中文為Chinese(Simplified)
英文為English

選擇語言

在彈出的窗口上點(diǎn)擊Finish即可
有使用Main.storyboardLaunchScreen.storyboard可以勾選這兩個

添加語言

完成后就會如下圖所示,這兩個文件就是當(dāng)前工程的簡體中文英文配置文件

4 簡單使用

配置文件填寫對應(yīng)的文字

英文

簡體中文

加載對應(yīng)文字的時候如下

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)

模擬器語言為英文和簡體中文狀態(tài)下的展示結(jié)果

模擬器語言為英文

模擬器語言為簡體中文

5 手動切換語言

創(chuàng)建國際化語言管理工具類

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!)
    }
    
    /// 設(shè)置當(dāng)前語言
    ///
    /// - Parameter language: 當(dāng)前語言
    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()
    }
    
    /// 當(dāng)前語言
    ///
    /// - Returns: 當(dāng)前語言類型
    public func current() -> String {
        return UserDefaults.standard.value(forKey: UserLanguage) as! String
    }
}

APPdelegate中調(diào)用,建議在Window加載前調(diào)用,就不會出現(xiàn)因?yàn)榧虞d過快導(dǎo)致第一個界面語言沒有國際化的現(xiàn)象

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
    }

加載文字時,直接調(diào)用工具類的方法即可

label.text = InternationalTool.shared.string("國際化語言展示")

創(chuàng)建界面進(jìn)行手動切換語言

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名稱國際化

創(chuàng)建Strings File文件,并命名為InfoPlist.strings

選中創(chuàng)建好的文件,點(diǎn)擊右側(cè)Localize...

在彈出的窗口中點(diǎn)擊Localize

在右側(cè)勾選語言

配置InfoPlist.strings

CFBundleDisplayName = ""

效果如下

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容