Localization on the fly with localized Storyboards

后端 未结 2 1949
遇见更好的自我
遇见更好的自我 2021-02-09 21:06

I\'m working on an app that has a toggle button to switch between English and Arabic language and should be on the fly. I\'m using the method in https://github.com/maximbilan/io

相关标签:
2条回答
  • 2021-02-09 21:20

    I ended up by moving the arabic storyboard outside and name it Main-AR, then adding an extension in UIStoryboard to swizzle and initializer of storyboard to add -AR to the end of the storyboard name if i'm on arabic mode.

    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)
    }
    }
    
    0 讨论(0)
  • 2021-02-09 21:26

    change the bundle which is used to init the storyboard:

            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())
    

    although this change the storyboard based on language but do not load images! :(

    0 讨论(0)
提交回复
热议问题