I\'m interested in setting some text into a UILabel
, and depending on the directionality of the language (e.g., Hebrew - right-to-left [RTL], English - left-to-righ
There is a solution that is based on the language detection of the string.
Method returns NSTextAlignmentNatural
if direction can not be identified.
@implementation NSString (StringAlignmentDetection)
- (NSTextAlignment)naturalTextAligment
{
NSArray *tagschemes = [NSArray arrayWithObjects:NSLinguisticTagSchemeLanguage, nil];
NSLinguisticTagger *tagger = [[NSLinguisticTagger alloc] initWithTagSchemes:tagschemes options:0];
[tagger setString:self];
NSString *language = [tagger tagAtIndex:0 scheme:NSLinguisticTagSchemeLanguage tokenRange:NULL sentenceRange:NULL];
NSTextAlignment alignment = NSTextAlignmentNatural;
if(!language)
{
return alignment;
}
NSLocaleLanguageDirection direction = [NSLocale characterDirectionForLanguage: language];
switch (direction)
{
case NSLocaleLanguageDirectionLeftToRight:
alignment = NSTextAlignmentLeft;
break;
case NSLocaleLanguageDirectionRightToLeft:
alignment = NSTextAlignmentRight;
break;
default:
alignment = NSTextAlignmentNatural;
break;
}
return alignment;
}
@end