首页投稿(暂停使用,暂停投稿)IOS

iOS国际化切换 for Swift

2017-10-31  本文已影响192人  程序H

公司业务做到了国外,要做给印度尼西亚使用的APP,需要在APP内部直接切换语言,而不是根据系统语言而显示不同的语言,经过一番调研做了一个简单的Demo,分享学习成果的同时自己也做个总结。

国际惯例先上效果图

效果图

准备工作

这里需要提醒一下,如何查看国家对应语言代码,笔者在调研过程中各种搜索也无果,后自己发现 添加语言时()里即为国家对应语言代码,后面写代码时会用到,具体如下图。

()里为国家对应语言代码

代码实现

创建CustomLanguage工具类,其中语言代码如何查看上文已提到,如下:

class CustomLanguage: NSObject {
    //单例
    static let share = CustomLanguage()
    // 国家语言代码
    var lan = ""
    
    func showText(key: String) -> String {
        // 查找对应国家语言代码的路径
        guard let path = Bundle.main.path(forResource: lan, ofType: "lproj") else { return "" }
        // 通过路径在CustomLacation语言文件中查找对应key的字符串
        guard let bundle = Bundle(path: path)?.localizedString(forKey: key, value: nil, table: "CustomLacation") else { return "" }
        return bundle
    }
}

四个按钮的点击方法,其中setAttributedWithImage方法是封装的富文本类别,可在github中下载源码查看。

@objc func englishBtnClick() {
    CustomLanguage.share.lan = "en"
    label.attributedText = CustomLanguage.share.showText(key: "showText").setAttributedWithImage(subText: CustomLanguage.share.showText(key: "showText"), subColor: #colorLiteral(red: 0.2196078449, green: 0.007843137719, blue: 0.8549019694, alpha: 1), image: UIImage(named: CustomLanguage.share.showText(key: "image"))!)
}


@objc func chineseSimpleBtnClick() {
    CustomLanguage.share.lan = "zh-Hans"
    label.attributedText = CustomLanguage.share.showText(key: "showText").setAttributedWithImage(subText: CustomLanguage.share.showText(key: "showText"), subColor: #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1), image: UIImage(named: CustomLanguage.share.showText(key: "image"))!)
}

@objc func chineseTWBtnClick() {
    CustomLanguage.share.lan = "zh-Hant"
    label.attributedText = CustomLanguage.share.showText(key: "showText").setAttributedWithImage(subText: CustomLanguage.share.showText(key: "showText"), subColor: #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1), image: UIImage(named: CustomLanguage.share.showText(key: "image"))!)
}

@objc func indonesiaBtnClick() {
    CustomLanguage.share.lan = "id"
    label.attributedText = CustomLanguage.share.showText(key: "showText").setAttributedWithImage(subText: CustomLanguage.share.showText(key: "showText"), subColor: #colorLiteral(red: 0.2745098174, green: 0.4862745106, blue: 0.1411764771, alpha: 1), image: UIImage(named: CustomLanguage.share.showText(key: "image"))!)
}

如果感兴趣可以到我的github中下载源码,记得点击Stars哈,感谢。

上一篇 下一篇

猜你喜欢

热点阅读