An easier way to detect text input direction

I want to determine the recording direction of a string so that I can correctly display languages ​​from right to left, such as Arabic, in 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; } 

It works fine, but it feels a little heavy just to find out how to align the text, especially because it was called in drawInContext (albeit relatively rarely).

Is there an easier way to determine the recording direction for a given line, or should I just stick to this at the heart of premature optimization. And it should become iOS 5 friendly.

+6
source share
3 answers

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

Most of the answers are here in NSString Language Discovery

better shape so ...

 +(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; } 

Since Arabic and Hebrew are the only Right-to-Left languages ​​defined by CFStringTokenizerCopyBestStringLanguage and should also cover Persian, Urdu and Yiddish, although I have not tested this.

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

+13
source

Since UITextAlignment is deprecated, here is the NSString category with NSWritingDirection:

 - (NSWritingDirection)alignment{ if (self.length) { NSArray *rightLeftLanguages = @[@"ar",@"he"]; NSString *lang = CFBridgingRelease(CFStringTokenizerCopyBestStringLanguage((CFStringRef)self,CFRangeMake(0,self.length))); if ([rightLeftLanguages containsObject:lang]) { return NSWritingDirectionRightToLeft; } } return NSWritingDirectionLeftToRight; 

}

+1
source

Swift

For me .natural textAlignment of UITextView did not work unless I edited the text and line from the beginning.

Based on an excellent answer to this question and comment below .

 let text = "..." let lang = CFStringTokenizerCopyBestStringLanguage(text as CFString, CFRange(location: 0, length: text.characters.count)) if let lang = lang { let direction = NSLocale.characterDirection(forLanguage: lang as String) if direction == .rightToLeft { textView.textAlignment = .right } else { textView.textAlignment = .left } } 
0
source

Source: https://habr.com/ru/post/943923/


All Articles