Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextView alignment for 'right to left' written language

I have created two methods to change the text alignment of a UITextView. I am targeting iOS6 and above. The idea is that the user can change the alignment of the input of the textview. if the input is in English, below methods are working fine. If the inputs in Arabic, It wont change the alignment.

-(void) changeLeftAllignment
{
    myTextView.textAlignment = NSTextAlignmentLeft;
}

-(void) changeRightAllignment
{
    myTextView.textAlignment = NSTextAlignmentRight;
}

This works perfectly for only English input. If I change the keyboard language to Arabic which is from right to left, it doesn't work anymore.

Any idea to solve this issue?

Thanks

like image 794
iMubarak Avatar asked Dec 03 '25 10:12

iMubarak


1 Answers

From iOS 6.0+ you should use NSTextAlignmentNatural. The UITextAlignment enumerated is deprecated. If you run your code on an iOS 6.0 target, it will automatically use natural alignment and all will work as expected.

In previous versions of iOS, you could check whether the language input is RTL and invert your alignment:

- (BOOL)isRTL {
  return ([NSLocale characterDirectionForLanguage:[[NSLocale preferredLanguages] objectAtIndex:0]] == NSLocaleLanguageDirectionRightToLeft);
}

-(void) changeLeftAllignment
{
    myTextView.textAlignment = (![self isRTL]]) ? UITextAlignmentLeft : UITextAlignmentRight;
}

-(void) changeRightAllignment
{
    myTextView.textAlignment = (![self isRTL]]) ? UITextAlignmentRight : UITextAlignmentLeft;
}
like image 134
Daniel Martín Avatar answered Dec 04 '25 23:12

Daniel Martín



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!