Localization on the fly with localized Storyboards

后端 未结 2 1948
遇见更好的自我
遇见更好的自我 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)
    }
    }
    

提交回复
热议问题