Automatically align text in UILabel according to text language

后端 未结 5 572
-上瘾入骨i
-上瘾入骨i 2021-02-04 19:59

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

5条回答
  •  -上瘾入骨i
    2021-02-04 20:27

    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
    

提交回复
热议问题