Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

ios - A lighter way of discovering text writing direction

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

+(UITextAlignment)alignmentForString:(NSString *)astring
{
    UITextView *text = [[UITextView alloc] initWithFrame:CGRectZero];
    text.text = astring;

    if ([text baseWritingDirectionForPosition:[text beginningOfDocument] inDirection:UITextStorageDirectionForward] == UITextWritingDirectionRightToLeft) {
        return UITextAlignmentRight;
    }

    return UITextAlignmentLeft;

}

Works fine but feels a little heavy just for the purpose of discovering which way to align my text especially as its been called in drawInContext (although relatively infrequently).

Is there a lighter way of determining the writing direction for a given string or should I just stick with this under the basis of premature optimisation. And its got to be iOS 5 friendly.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...