swiftui中本地化我们的应用程序过程中,有一些变量也需要进行本地化

1.首先在localizable.string文件中添加本地化转换

“AppName”=”我的一款很酷的应用”;

2.添加一个枚举,这里我添加了一个枚举文件

enum myenum{

    internal static let AppName:LocalizedStringKey = LocalizedStringKey(“AppName”)

}

3.添加一个转换的扩展

extension LocalizedStringKey {

    /**

     Return localized value of thisLocalizedStringKey

     */

    public func toString() -> String {

        //use reflection

        let mirror = Mirror(reflecting: self)

        

        //try to find ‘key’ attribute value

        let attributeLabelAndValue = mirror.children.first { (arg0) -> Bool in

            let (label, _) = arg0

            if(label == “key”){

                return true;

            }

            return false;

        }

        

        if(attributeLabelAndValue != nil) {

            //ask for localization of found key via NSLocalizedString

            return String.localizedStringWithFormat(NSLocalizedString(attributeLabelAndValue!.value as! String, comment: “”));

        }

        else {

            return “Swift LocalizedStringKey signature must have changed. @see Apple documentation.”

        }

    }

}

4.如此,以后添加变量就可以直接通地这个扩展转换了

使用举例:

let AppNameString=myenum.AppName.toString()

以后将需要国际化的变量放到enum中,同时在ocalizable.string文件中添加对应的转换,就可以直接使用tostring的扩展

 

发表评论

后才能评论