即时本地化:使用本地化故事板进行本地化

6
我正在开发一款应用程序,其中有一个切换按钮,可以在英语和阿拉伯语之间进行切换,并且应该是实时的。我使用https://github.com/maximbilan/ios_language_manager中的方法,在所有情况下都可以正常工作,除非故事板是通过接口而不是字符串本地化的:

enter image description here

当我像这样重新加载根视图控制器时:
   func reloadRootVC(){

    let delegate : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

    let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())

    delegate.window?.rootViewController = (storyboard.instantiateInitialViewController())
}

该IT技术相关内容需要重新加载具有本地化字符串和RTL的根,但使用的是英语storyboard而不是阿拉伯语。

尝试通过以下方式强制加载阿拉伯语版本:

let storyboard = UIStoryboard(name: "Main", bundle: NSBundle(path: NSBundle.mainBundle().pathForResource(LanguageManager.currentLanguageCode(), ofType: "lproj")!))

但不幸的是,它加载了故事板却没有图片。它无法读取任何资源图像。


很不幸,你将会在接口方面遇到很多麻烦,同时也会遇到从右到左的用户界面无法正确显示的问题,更不用说格式化程序和本地化格式字符串不能正确运行的问题了。一般来说,应用程序应该遵循系统语言,而不是实现一个应用内的语言切换器... 这样做将会在长期运行中为你省去很多麻烦。 :( - wakachamo
2个回答

2

更改用于初始化storyboard的bundle:

        let path = Bundle.main.path(forResource: "ar", ofType: "lproj")
        let bundle = Bundle(path: path!)
        let delegate : AppDelegate = UIApplication.shared.delegate as! AppDelegate
        let storyboard = UIStoryboard(name: "Main", bundle: bundle)
        delegate.window?.rootViewController = (storyboard.instantiateInitialViewController())

尽管这会根据语言更改故事板,但不会加载图像!:(

2

我最终将阿拉伯语的故事板移出并命名为Main-AR,然后在UIStoryboard中添加了一个扩展来交换和初始化故事板,如果我处于阿拉伯语模式,则在故事板名称末尾添加-AR

extension UIStoryboard {
public override class func initialize() {
    struct Static {
        static var token: dispatch_once_t = 0
    }

    // make sure this isn't a subclass
    if self !== UIStoryboard.self {
        return
    }

    dispatch_once(&Static.token) {
        let originalSelector = #selector(UIStoryboard.init(name:bundle:))
        let swizzledSelector = #selector(UIStoryboard.initWithLoc(_:bundle:))

        let originalMethod = class_getClassMethod(self, originalSelector)
        let swizzledMethod = class_getClassMethod(self, swizzledSelector)

        class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))

        method_exchangeImplementations(originalMethod, swizzledMethod)

    }
}

// MARK: - Method Swizzling

class func initWithLoc(name: String, bundle storyboardBundleOrNil: NSBundle?) -> UIStoryboard{
    var newName = name
    if LanguageManager.isCurrentLanguageRTL(){
        newName += "-AR"
        if #available(iOS 9.0, *) {
            UIView.appearance().semanticContentAttribute = .ForceRightToLeft
        } else {
            // Fallback on earlier versions

        }
    }
    else{
        if #available(iOS 9.0, *) {
            UIView.appearance().semanticContentAttribute = .ForceLeftToRight
        } else {
            // Fallback on earlier versions
        }
    }
    return initWithLoc(newName, bundle: storyboardBundleOrNil)
}
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接