A lighter way of discovering text writing direction

后端 未结 3 1215
南方客
南方客 2020-12-09 22:59

I want to determine the writing direction of a string so that I can render Right-to-Left languages such as Arabic correctly in a CALayer.

so I have this method

3条回答
  •  我在风中等你
    2020-12-09 23:17

    The code in the question although functional is brutally expensive. Run it through a profiler and you will find that it spends close to 80% of the time in UITextView.setText when used in the drawInContext method for a layer.

    Most of the answer is here in Detect Language of NSString

    a better form is thus...

    +(UITextAlignment)alignmentForString:(NSString *)astring
    {
    
        if (astring.length) {
    
            NSArray *rightLeftLanguages = @[@"ar",@"he"];
    
            NSString *lang = CFBridgingRelease(CFStringTokenizerCopyBestStringLanguage((CFStringRef)astring,CFRangeMake(0,[astring length])));
    
            if ([rightLeftLanguages containsObject:lang]) {
    
                return UITextAlignmentRight;
    
            }
        }
    
        return UITextAlignmentLeft;
    
    }
    

    As Arabic and Hebrew are the only Right-to-Left languages detectable by CFStringTokenizerCopyBestStringLanguage and should also cover Persian, Urdu and Yiddish though I havent tested that.

    see also http://en.wikipedia.org/wiki/Right-to-left

提交回复
热议问题