我需要将语言从英语更改为阿拉伯语。应用程序中的所有UI都是以编程方式开发的,我没有将Storyboard / xib用于UI。我使用了本地化字符串来转换语言,但是我正在寻找从LTR到RTL的UI视图,反之亦然。
什么是语言变化的最佳方式,并给我一些想法或样品
答案 0 :(得分:1)
您可以通过以下方法检查当前语言:
open class func isCurrentLanguageRTL(language:String) -> Bool {
return Locale.characterDirection(forLanguage: language) == .rightToLeft
}
使用此目标C代码(类别),您可以更改UI RTL:
#import <Foundation/Foundation.h>
@interface NSBundle (Language)
+ (void)setLanguage:(NSString *)language;
@end
执行文件:
#import "NSBundle+Language.h"
#import <UIKit/UIKit.h>
#import <objc/runtime.h>
static const char kBundleKey = 0;
@interface BundleEx : NSBundle
@end
@implementation BundleEx
- (NSString *)localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)tableName
{
NSBundle *bundle = objc_getAssociatedObject(self, &kBundleKey);
if (bundle) {
return [bundle localizedStringForKey:key value:value table:tableName];
}
else {
return [super localizedStringForKey:key value:value table:tableName];
}
}
@end
@implementation NSBundle (Language)
+ (void)setLanguage:(NSString *)language
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
object_setClass([NSBundle mainBundle], [BundleEx class]);
});
if ([self isCurrentLanguageRTL:language]) {
if ([[[UIView alloc] init] respondsToSelector:@selector(setSemanticContentAttribute:)]) {
[[UIView appearance] setSemanticContentAttribute:UISemanticContentAttributeForceRightToLeft];
[[UITableView appearance] setSemanticContentAttribute:UISemanticContentAttributeForceRightToLeft];
[[UINavigationBar appearance] setSemanticContentAttribute:UISemanticContentAttributeForceRightToLeft];
}
}else {
if ([[[UIView alloc] init] respondsToSelector:@selector(setSemanticContentAttribute:)]) {
[[UIView appearance] setSemanticContentAttribute:UISemanticContentAttributeForceLeftToRight];
[[UITableView appearance] setSemanticContentAttribute:UISemanticContentAttributeForceLeftToRight];
[[UINavigationBar appearance] setSemanticContentAttribute:UISemanticContentAttributeForceLeftToRight];
}
}
[[NSUserDefaults standardUserDefaults] setBool:[self isCurrentLanguageRTL:language] forKey:@"AppleTextDirection"];
[[NSUserDefaults standardUserDefaults] setBool:[self isCurrentLanguageRTL:language] forKey:@"NSForceRightToLeftWritingDirection"];
[[NSUserDefaults standardUserDefaults] synchronize];
id value = language ? [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:language ofType:@"lproj"]] : nil;
objc_setAssociatedObject([NSBundle mainBundle], &kBundleKey, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
+ (BOOL)isCurrentLanguageRTL:(NSString *)code
{
return ([NSLocale characterDirectionForLanguage:code] == NSLocaleLanguageDirectionRightToLeft);
}
@end
使用方法:
任何类型的语言(如RTL,LTR)仅在您的代码中调用此bundle函数:
Bundle.setLanguage(<#Your Language code#>)
注意:您应该在桥接标头文件中添加#import "NSBundle+Language.h"
。
如果使用的是左侧菜单,而不是RTL,则必须从右侧打开菜单,只需检查上述快捷功能即可:
<#YourClass#>.isCurrentLanguageRTL(<#Your Language Code#>) {
//open your side menu from right
}