Reputation: 852
I created localization for my storyboard (English, Arabic) and I did the function that changes (switch) the App. language (local) it's working perfect if I restart (relaunch) the app manually and my Views flip Right-Let if Arabic and Left-Right if English as well, but how can I change the storyboard local without restarting my app manually?.
I used this function to change the language
func setLocale(langCode:String){
NSUserDefaults.standardUserDefaults().setObject([langCode], forKey: "AppleLanguages")
NSUserDefaults.standardUserDefaults().synchronize()
}
Thank in advance.
Upvotes: 5
Views: 8616
Reputation: 7212
I was looking for same answer today and I could't find it, but I used this code
let vc = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController
UIApplication.shared.keyWindow?.rootViewController = vc
to reload the main view controller and it did some how restart the app, although there was some problems with connected views to storyboard that I removed them from superView...
Upvotes: 0
Reputation: 2187
This is how you can do. However this code is in Obj-C.
Create a category class for NSBundle like this:
#import "NSBundle+ForceLocalization.h"
#import <objc/runtime.h>
static const char _bundle=0;
@interface BundleEx : NSBundle
@end
@implementation BundleEx
-(NSString*)localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)tableName
{
NSBundle* bundle=objc_getAssociatedObject(self, &_bundle);
return bundle ? [bundle localizedStringForKey:key value:value table:tableName] : [super localizedStringForKey:key value:value table:tableName];
}
@end
@implementation NSBundle (ForceLocalization)
+(void)setLanguage:(NSString*)language
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^
{
object_setClass([NSBundle mainBundle],[BundleEx class]);
});
objc_setAssociatedObject([NSBundle mainBundle], &_bundle, language ? [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:language ofType:@"lproj"]] : nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
After this, simply call:
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects: langCode, nil]
forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];
[NSBundle setLanguage: langCode];
You need to reload the UI for the current screen again. If you go on to another controller, you'll see the updated language.
Upvotes: 3